Interview

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.

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.

JavaScript Regular Expression Interview Questions and Answers

1. Write a regex pattern to match a string that starts with “abc” and ends with “xyz”.

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

2. Write a regex to match a string that contains exactly three consecutive vowels.

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

3. Construct a regex to match a string that starts with a capital letter and ends with a period.

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

4. Write a regex to capture the domain name from an email address.

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.

5. Create a regex to match a string that does not contain the word “error”.

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

6. Write a regex to match a string that includes a dollar sign followed by one or more digits.

To match a string that includes a dollar sign followed by one or more digits, use the following regular expression:

const regex = /\$\d+/;

Explanation:

  • The backslash \ is used to escape the dollar sign $, which is a special character in regular expressions.
  • \d matches any digit.
  • The + 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

7. Write a regex to replace all instances of “foo” with “bar” in a given string.

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"

8. Write a regex to find repeated words in a string, such as “the the”.

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"]

9. Write a regex using lookaheads to match a string that contains “foo” only if it is followed by “bar”.

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.

10. Write a regex using non-capturing groups to match a sequence of digits separated by commas without capturing the commas.

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"
Previous

10 Slowly Changing Dimensions Interview Questions and Answers

Back to Interview
Next

10 NFS Server Interview Questions and Answers