Regular Expressions in JavaScript — Interview Questions & Answers
Ques: What is a Regular Expression in JavaScript?
Ans: A Regular Expression (RegExp) is an object used for matching text patterns in strings. It helps you search, replace, or validate string data efficiently.
Example:
const pattern = /hello/;
console.log(pattern.test("hello world")); // true
Ques: How can you create a Regular Expression in JavaScript?
Ans: There are two ways:
Literal syntax:
const regex = /abc/;
Constructor function:
const regex = new RegExp("abc");
Ques: What are RegExp flags in JavaScript?
Ans: Flags modify how the regular expression behaves.
| Flag | Name | Description |
|---|---|---|
g | Global | Match all occurrences |
i | Ignore Case | Case-insensitive match |
m | Multiline | Match across multiple lines |
s | Dotall | . matches newline (\\n) |
u | Unicode | Enables full Unicode support |
y | Sticky | Matches from lastIndex position |
Example:
const re = /hello/gi;
Ques: What are some common RegExp methods in JavaScript?
| Method | Used On | Description |
|---|---|---|
test() | RegExp | Returns true/false |
exec() | RegExp | Returns match details |
match() | String | Returns match array |
matchAll() | String | Returns all matches (iterator) |
replace() | String | Replaces matched text |
search() | String | Returns index of first match |
split() | String | Splits string by regex pattern |
Ques: How do you perform a case-insensitive match?
Ans: Use the i flag.
const re = /hello/i;
console.log(re.test("HELLO")); // true
Ques: What is the difference between String.match() and String.matchAll()?
match()returns an array (or null)matchAll()returns an iterator (ES2020)
const text = "cat bat mat";
console.log(text.match(/.at/g)); // ['cat', 'bat', 'mat']
console.log([...text.matchAll(/.at/g)]);
Ques: What are anchors in Regular Expressions?
Ans: Anchors are used to match positions, not characters.
| Anchor | Description |
|---|---|
^ | Start of string |
$ | End of string |
\\b | Word boundary |
\\B | Non-word boundary |
Example:
/^Hello/.test("Hello JS"); // true
/JS$/.test("I love JS"); // true
Ques: What are character classes?
Ans: They define sets of characters to match.
| Pattern | Matches |
|---|---|
[abc] | a, b, or c |
[^abc] | any char except a, b, or c |
[a-z] | lowercase letters |
[A-Z] | uppercase letters |
[0-9] | digits 0–9 |
Example:
/[A-Z]/.test("Hello"); // true
Ques: What are predefined character classes?
| Pattern | Meaning |
|---|---|
\\d | Digit (0–9) |
\\D | Non-digit |
\\w | Word char (A–Z, a–z, 0–9, _) |
\\W | Non-word char |
\\s | Whitespace |
\\S | Non-whitespace |
. | Any character except newline |
Example:
/\\d\\d/.test("Year2025"); // true
Ques: What are quantifiers in RegExp?
Ans: They define how many times a pattern should appear.
| Quantifier | Description | Example |
|---|---|---|
+ | One or more | /a+/ → "aa" |
* | Zero or more | /go*/ → "g", "gooo" |
? | Zero or one | /colou?r/ → "color" or "colour" |
{n} | Exactly n times | /\\d{4}/ |
{n,} | At least n times | /\\d{2,}/ |
{n,m} | Between n and m | /\\d{2,4}/ |
Ques: Example of using quantifiers
const re = /\\d{3}-\\d{2}-\\d{4}/;
console.log(re.test("123-45-6789")); // true
Ques: What is the purpose of parentheses ( ) in RegExp?
Ans: Parentheses are capturing groups — they store matched substrings.
const re = /(\\d{2})-(\\d{2})-(\\d{4})/;
const result = re.exec("27-10-2025");
console.log(result[1]); // "27"
Ques: How do you create a non-capturing group?
Ans: Use (?: ) to group without capturing.
const re = /(?:Mr|Ms)\\.?\\s[A-Z]/;
Ques: What is the use of alternation (|)?
Ans: The | operator means “OR”.
const re = /cat|dog/;
console.log(re.test("I have a dog")); // true
Ques: What does \\b mean in regex?
Ans: \\b matches word boundaries, ensuring complete word matches.
/\\bcat\\b/.test("catfish"); // false
/\\bcat\\b/.test("my cat"); // true
Ques: Example: Validate an Email Address
const emailRegex = /^[\\w.-]+@[a-zA-Z_-]+?\\.[a-zA-Z]{2,}$/;
console.log(emailRegex.test("[email protected]")); // true
Ques: Example: Extract Numbers from String
const str = "Order 45 has 3 items";
console.log(str.match(/\\d+/g)); // ['45', '3']
Ques: How can you replace matched text using regex?
Ans: Use String.replace() with a pattern.
const str = "Hello 2025";
console.log(str.replace(/\\d+/, "World")); // "Hello World"
Ques: How do you use backreferences in regex?
Ans: Backreferences recall previously captured groups using \\1, \\2, etc.
const re = /(\\w+)\\s\\1/;
console.log(re.test("bye bye")); // true
Ques: What are lookaheads and lookbehinds?
Ans: They allow matching without consuming characters.
| Type | Syntax | Description |
|---|---|---|
| Positive Lookahead | X(?=Y) | Match X if followed by Y |
| Negative Lookahead | X(?!Y) | Match X if not followed by Y |
| Positive Lookbehind | (?<=Y)X | Match X if preceded by Y |
| Negative Lookbehind | (?<!Y)X | Match X if not preceded by Y |
Example:
/\\d(?=px)/.test("10px"); // true
/\\d(?!px)/.test("10em"); // true
Ques: Example: Match a password pattern
const password = /^(?=.*[A-Z])(?=.*\\d)(?=.*[@$!%*?&]).{8,}$/;
console.log(password.test("MyPass@123")); // true
Ques: How to escape special characters in regex?
Ans: Use a backslash \\.
const re = /\\./; // matches literal dot
Ques: How to split a string using regex?
const text = "HTML, CSS; JS";
console.log(text.split(/[,;]\\s*/)); // ['HTML', 'CSS', 'JS']
Ques: Can regex be used for Unicode characters?
Ans: Yes, using the u flag.
const re = /\\u{1F600}/u; // 😀
Ques: What are greedy and lazy quantifiers?
| Type | Example | Description |
|---|---|---|
| Greedy | /".+"/ | Matches as much as possible |
| Lazy | /".+?"/ | Matches as little as possible |
Example:
const str = '"one" "two"';
console.log(str.match(/".+?"/g)); // ["one", "two"]
Ques: How do you debug or visualize regex patterns?
Use online tools like regex101.com or regexr.com for explanations and testing.
Ques: Can regex work across multiple lines?
Ans: Yes, using the m flag.
/^start/m.test("line1\nstart line2"); // true
