J

JavaScript Handbook

Clean • Professional

JavaScript Regular Expressions — Top Interview Q&A

4 minute

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.

FlagNameDescription
gGlobalMatch all occurrences
iIgnore CaseCase-insensitive match
mMultilineMatch across multiple lines
sDotall. matches newline (\\n)
uUnicodeEnables full Unicode support
yStickyMatches from lastIndex position

Example:

const re = /hello/gi;

Ques: What are some common RegExp methods in JavaScript?

MethodUsed OnDescription
test()RegExpReturns true/false
exec()RegExpReturns match details
match()StringReturns match array
matchAll()StringReturns all matches (iterator)
replace()StringReplaces matched text
search()StringReturns index of first match
split()StringSplits 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.

AnchorDescription
^Start of string
$End of string
\\bWord boundary
\\BNon-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.

PatternMatches
[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?

PatternMeaning
\\dDigit (0–9)
\\DNon-digit
\\wWord char (A–Z, a–z, 0–9, _)
\\WNon-word char
\\sWhitespace
\\SNon-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.

QuantifierDescriptionExample
+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.

TypeSyntaxDescription
Positive LookaheadX(?=Y)Match X if followed by Y
Negative LookaheadX(?!Y)Match X if not followed by Y
Positive Lookbehind(?<=Y)XMatch X if preceded by Y
Negative Lookbehind(?<!Y)XMatch 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?

TypeExampleDescription
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

 

Article 0 of 0