JavaScript Interview Question #186
What are regular expressions in JavaScript?
Advanced JavaScript, Practical Problems & Senior Interview Scenarios Senior Advanced
Quick Interview Answer
A regular expression describes a text pattern used for searching, matching, validation, extraction, and replacement. JavaScript supports regex literals and the RegExp constructor.
Detailed Explanation
A regular expression describes a text pattern used for searching, matching, validation, extraction, and replacement. JavaScript supports regex literals and the RegExp constructor.
Regular expressions are useful for well-defined text patterns, but complex validation rules can become difficult to read and maintain. Input validation should also consider business rules rather than relying only on a pattern.
Code Example
const emailLike =
/^[^\s@]+@[^\s@]+\.[^\s@]+$/;
console.log(
emailLike.test("user@example.com")
); // true
const text = "Order 12345";
console.log(text.match(/\d+/)?.[0]); // 12345