10 JavaScript Regular Expression Interview Questions and Answers
Prepare for your next interview with this guide on JavaScript Regular Expressions. Enhance your skills with common and advanced regex questions and answers.
Prepare for your next interview with this guide on JavaScript Regular Expressions. Enhance your skills with common and advanced regex questions and answers.
JavaScript Regular Expressions (regex) are powerful tools for pattern matching and text manipulation. They are essential for tasks such as form validation, search and replace operations, and data parsing. Mastering regex can significantly enhance your ability to handle complex string operations efficiently, making it a valuable skill in any developer’s toolkit.
This article provides a curated selection of interview questions focused on JavaScript Regular Expressions. By working through these questions and their detailed answers, you will gain a deeper understanding of regex concepts and improve your problem-solving abilities, preparing you to tackle technical interviews with confidence.
To match a string that starts with “abc” and ends with “xyz” using a regular expression in JavaScript, use the following pattern:
const regex = /^abc.*xyz$/;
Explanation:
^
asserts the position at the start of the string.abc
matches the literal characters “abc”..*
matches any character (except for line terminators) between zero and unlimited times.xyz
matches the literal characters “xyz”.$
asserts the position at the end of the string.Example usage:
const regex = /^abc.*xyz$/; const testString1 = "abc123xyz"; const testString2 = "abcxyz"; const testString3 = "123abcxyz"; console.log(regex.test(testString1)); // true console.log(regex.test(testString2)); // true console.log(regex.test(testString3)); // false
To match a string that contains exactly three consecutive vowels using a regular expression in JavaScript, use the following pattern:
const regex = /[aeiou]{3}/i;
This regular expression uses the character set [aeiou]
to match any vowel (a, e, i, o, u) and {3}
to specify that exactly three consecutive vowels should be matched. The i
flag makes the matching case-insensitive.
Example usage:
const testString1 = "beautiful"; const testString2 = "queueing"; const testString3 = "rhythm"; console.log(regex.test(testString1)); // true console.log(regex.test(testString2)); // true console.log(regex.test(testString3)); // false
To construct a regex that matches a string starting with a capital letter and ending with a period, use the following pattern:
const regex = /^[A-Z].*\.$/;
Here is a breakdown of the regex pattern:
^
asserts the position at the start of the string.[A-Z]
matches any uppercase letter from A to Z..*
matches any character (except for line terminators) zero or more times.\.
matches a literal period.$
asserts the position at the end of the string.Example usage in JavaScript:
const regex = /^[A-Z].*\.$/; const testString1 = "Hello world."; const testString2 = "hello world."; const testString3 = "Hello world"; console.log(regex.test(testString1)); // true console.log(regex.test(testString2)); // false console.log(regex.test(testString3)); // false
Regular expressions (regex) are powerful tools for pattern matching and string manipulation. In JavaScript, regex can be used to capture specific parts of a string, such as the domain name from an email address. The regex pattern for capturing the domain name involves identifying the part of the email address that comes after the “@” symbol and before any subsequent characters.
Example:
const email = "[email protected]"; const regex = /@([a-zA-Z0-9.-]+\.[a-zA-Z]{2,})/; const match = email.match(regex); if (match) { console.log(match[1]); // Output: domain.com }
In this example, the regex pattern @([a-zA-Z0-9.-]+\.[a-zA-Z]{2,})
is used to capture the domain name. The pattern can be broken down as follows:
@
matches the “@” symbol.([a-zA-Z0-9.-]+)
captures one or more alphanumeric characters, dots, or hyphens, which represent the domain name.\.
matches the dot before the top-level domain (TLD).[a-zA-Z]{2,}
captures the TLD, which consists of at least two alphabetic characters.To create a regex that matches a string not containing the word “error,” use a negative lookahead assertion. Negative lookahead ensures that a certain pattern is not present in the string.
The regex pattern for this requirement is:
^(?!.*\berror\b).*$
Explanation:
^
asserts the position at the start of the string.(?!)
is the negative lookahead assertion..*
matches any character (except for line terminators) zero or more times.\berror\b
matches the word “error” as a whole word..*$
matches the rest of the string.Example usage in JavaScript:
const regex = /^(?!.*\berror\b).*$/; console.log(regex.test("This is a test string.")); // true console.log(regex.test("This string contains error.")); // false console.log(regex.test("Another test without the keyword.")); // true
To match a string that includes a dollar sign followed by one or more digits, use the following regular expression:
const regex = /\$\d+/;
Explanation:
\
is used to escape the dollar sign $
, which is a special character in regular expressions.\d
matches any digit.+
quantifier matches one or more of the preceding element (in this case, digits).Example usage:
const str1 = "$100"; const str2 = "Price: $50"; const str3 = "No match here"; console.log(regex.test(str1)); // true console.log(regex.test(str2)); // true console.log(regex.test(str3)); // false
To replace all instances of “foo” with “bar” in a given string using JavaScript, use the replace
method with a regular expression. The regular expression /foo/g
is used to find all occurrences of “foo” in the string. The g
flag stands for “global”, meaning it will match all instances, not just the first one.
Example:
let str = "foo is not bar, but foo is still foo"; let result = str.replace(/foo/g, "bar"); console.log(result); // "bar is not bar, but bar is still bar"
Regular expressions (regex) are a powerful tool for pattern matching and text manipulation. In JavaScript, regex can be used to find repeated words in a string by defining a pattern that matches any word followed by the same word.
The regex pattern for finding repeated words can be written as follows:
const regex = /\b(\w+)\s+\1\b/gi;
Explanation:
\b
asserts a word boundary.(\w+)
captures a word (one or more word characters).\s+
matches one or more whitespace characters.\1
refers to the first captured group (the word).\b
asserts another word boundary.gi
are flags for global search and case-insensitive matching.Example usage:
const text = "This is the the sample text with repeated repeated words."; const regex = /\b(\w+)\s+\1\b/gi; const matches = text.match(regex); console.log(matches); // Output: ["the the", "repeated repeated"]
Lookaheads in regular expressions are used to assert that a certain pattern is followed by another pattern without including the second pattern in the match. This is useful when you want to ensure that a string contains a specific sequence only if it is followed by another sequence.
To match a string that contains “foo” only if it is followed by “bar”, use a positive lookahead. The syntax for a positive lookahead is (?=...)
.
Example:
const regex = /foo(?=bar)/; const str1 = "foobar"; const str2 = "foobaz"; console.log(regex.test(str1)); // true console.log(regex.test(str2)); // false
In this example, the regular expression /foo(?=bar)/
matches “foo” only if it is immediately followed by “bar”. The test
method is used to check if the pattern exists in the given strings.
Non-capturing groups in regular expressions are used to group part of a pattern without capturing it for back-references. This is useful when you want to apply quantifiers to a group of patterns but do not need to capture the group for later use.
To match a sequence of digits separated by commas without capturing the commas, use the following regex pattern:
const regex = /\d+(?:,\d+)*/;
In this pattern:
\d+
matches one or more digits.(?:,\d+)
is a non-capturing group that matches a comma followed by one or more digits.*
applies the quantifier to the non-capturing group, allowing it to match zero or more times.Example usage:
const str = "123,456,789"; const regex = /\d+(?:,\d+)*/; const match = str.match(regex); console.log(match[0]); // Output: "123,456,789"