JavaScript Regular Expressions Interview Questions and Answers
Review JavaScript regular-expression syntax, flags, matching methods, and practical text validation.
Frequently Asked Questions
Important questions are highlighted in the sections below; select one to jump to its answer.
- What is a regular expression in JavaScript?
- What are regular expressions used for?
- Create a RegExp that matches a product-code format.
- What does the character class [A-Z] match?
- Check whether a string contains a digit
- What is the difference between match() and exec() when dealing with regular expressions?
- What are common regex flags and what do they do?
Theoretical JavaScript Interview Questions
The main string methods that accept a regex are match(), replace(), search(), and split(). The most useful are replace() with a regex (especially with capture groups for transforms) and match() with the g flag to get all matches. Remember: without the g flag, replace() and match() only operate on the first occurrence.
1. match(): Finds matches based on a regular expression.
let str = "Hello world!";
let result = str.match(/world/); // ["world"]
2. replace(): Replaces parts of a string that match a regular expression.
let str = "Hello world!";
let result = str.replace(/world/, "JavaScript"); // "Hello JavaScript!"
3. search(): Returns the index of the first match or -1 if not found.
let str = "Hello world!";
let index = str.search(/world/); // 6
4. split(): Splits a string based on a regular expression.
let str = "apple, banana, cherry";
let result = str.split(/,\s*/); // ["apple", "banana", "cherry"]
Regular Expression Flags:
- g: Global search (find all matches).
- i: Case-insensitive search.
- m: Multi-line search.
let str = "Hello hello";
let result = str.match(/hello/gi); // ["Hello", "hello"]
Regular expressions provide powerful pattern matching and string manipulation in JavaScript.
match() is called on a string and exec() is called on a regex - that's the main mental model. Without the g flag they behave similarly, both returning the first match with capture groups. With g: match() returns all matches as a flat array but drops capture groups, while exec() returns one match at a time with full capture group info and advances lastIndex. Use matchAll() (ES2020) if you need all matches with capture groups - it's the cleanest option now.
1. match():
- Used on strings.
- Returns an array of matches or null if no match is found.
- With the global (g) flag, it returns an array of all matches.
//Example without g flag:
let str = "Hello world";
let result = str.match(/world/); // ["world"]
//Example with `g` flag:
let str = "Hello world world";
let result = str.match(/world/g); // ["world", "world"]
2. exec():
- Used on regular expression objects.
- Returns an array with detailed match information, or null if no match is found.
- Only returns one match at a time, even with the global flag. It must be called repeatedly in a loop to get all matches.
let regex = /world/;
let result = regex.exec("Hello world"); // ["world"]
//With g flag and loop:
let regex = /world/g;
let str = "Hello world world";
let match;
while ((match = regex.exec(str)) !== null) {
console.log(match); // Logs each "world" match
}
Key Differences:
-
match()is simpler for straightforward matching on strings - use it withgto get all matches as an array. -
exec()is more powerful and provides full capture group details, but requires looping to get all matches when using thegflag.
A regular expression (regex) is a pattern used to match, search, or replace text. You describe a pattern and JavaScript checks if a string fits that pattern. They are useful for things like validating email addresses, extracting numbers from text, or replacing all occurrences of a word.
Flags are added after the closing slash and change how the regex behaves.
i- case insensitive, so/hello/imatches "Hello", "HELLO", etc.g- global, find all matches (not just the first one)m- multiline, makes^and$match the start/end of each lines- allows.to match newline characters too
const str = "Hello World hello";
console.log(str.match(/hello/gi)); // ["Hello", "hello"]
test() is a method on the regex object. It takes a string and returns true or false. Use it when you just want to know if the pattern matches. match() is a method on the string. It returns the actual matched text (or null if nothing matched). Use it when you want the matched values.
const pattern = /\d+/; // matches one or more digits
pattern.test("abc123"); // true
"abc123".match(pattern); // ["123"] - returns the match
Capture groups let you extract specific parts of a match by wrapping a part of the pattern in parentheses. Each group has a number starting from 1. Named capture groups (using ?<name>) make the code easier to read.
// Numbered groups
const match = "2024-06-15".match(/(\d{4})-(\d{2})-(\d{2})/);
console.log(match[1]); // 2024 (year)
console.log(match[2]); // 06 (month)
console.log(match[3]); // 15 (day)
// Named groups (cleaner)
const named = "2024-06-15".match(/(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/);
console.log(named.groups.year); // 2024
Use the g flag with replace() or use replaceAll(). With replace() and a regex, you can also use $1, $2 etc. to reference capture groups in the replacement string.
const str = "foo bar foo";
console.log(str.replace(/foo/g, "baz")); // "baz bar baz"
// Using capture group in replacement
const date = "2024-06-15";
console.log(date.replace(/(\d{4})-(\d{2})-(\d{2})/, "$3/$2/$1")); // "15/06/2024"
A lookahead lets you match something only if it is followed (or not followed) by something else, without including that "something else" in the match. Positive lookahead uses (?=...) and negative lookahead uses (?!...).
// Positive lookahead: match digits only if followed by "px"
"12px 5em 8px".match(/\d+(?=px)/g); // ["12", "8"]
// Negative lookahead: match digits NOT followed by "px"
"12px 5em 8px".match(/\d+(?!px)/g); // ["5"]
A regular expression describes a text pattern for matching, searching, validation, or replacement. It is not a full parser for every nested or context-sensitive language.
It matches one uppercase ASCII letter. It does not require an entire word to be uppercase unless repetition and suitable boundaries are also specified.
In ordinary regular-expression mode, ^ and $ match the start and end of the input (or line boundaries with the multiline flag). Anchors match positions rather than consuming characters.
JavaScript Practical and Coding Interview Questions
Problem: Use a global regular expression to collect every two-letter, four-digit product code from the sample text.
const text = 'AB-1234 and CD-5678 are valid; X-99 is not.';
const matches = text.match(/[A-Z]{2}-\d{4}/g) || [];
console.log(matches);Problem: Create a regular expression that matches two uppercase letters, a hyphen, and four digits, then test one valid and one invalid code.
const productCode = new RegExp('^[A-Z]{2}-\\d{4}$');
console.log(productCode.test('AB-1234'));
console.log(productCode.test('Ab-1234'));Problem: Implement hasDigit(text) using a regular expression and print results for one string containing a digit and one without.
function hasDigit(text) {
return /\d/.test(text);
}
console.log(hasDigit('room 7'));
console.log(hasDigit('empty room'));Problem: Write normalizeSpaces(text) to replace each run of whitespace with one ordinary space and trim both ends. Demonstrate tabs and repeated spaces.
function normalizeSpaces(text) {
return text.replace(/\s+/g, ' ').trim();
}
console.log(normalizeSpaces(' JavaScript\t regex '));