Regular expressions are JavaScript's pattern-matching engine. You'll need them for path parsing, string escaping, input validation, and search-and-replace. This article covers the syntax, flags, methods, and common patterns interviewers expect you to know.
1. Two Ways to Create a Regex
Loading editor...
Use the constructor when the pattern comes from a variable or includes user input (which must be escaped).
2. Flags
| Flag | Name | What It Does |
|---|---|---|
g | Global | Find all matches, not just the first |
i | Case-insensitive | Ignore case |
m | Multiline | ^ and $ match line boundaries |
s | DotAll | . matches \n too |
u | Unicode | Enable Unicode features |
y | Sticky | Match at lastIndex exactly |
Loading editor...
3. test() — Returns Boolean
Loading editor...
With the g flag, test() advances lastIndex — a surprising stateful behavior:
Loading editor...
When using g with test, reset lastIndex or avoid g if you just want a boolean.
4. exec() — Returns Match Details
Loading editor...
With the g flag, exec() advances lastIndex — call it repeatedly to get all matches.
5. String Methods That Accept Regex
match(regex) — Find Matches
Loading editor...
matchAll(regex) — All Matches with Details
Loading editor...
replace(regex, replacement) — Replace Matches
Loading editor...
Interview use: Path notation conversion (#16 — [0] → .0), JSON string escaping (#17).
search(regex) — Index of First Match
Loading editor...
split(regex) — Split by Pattern
Loading editor...
Interview use: Parsing dot/bracket paths (#6), parsing multi-class strings (#24).
6. Character Classes
Loading editor...
7. Quantifiers
Loading editor...
8. Anchors and Boundaries
Loading editor...
9. Groups and Alternation
Loading editor...
10. Lookahead and Lookbehind
Loading editor...
11. Common Patterns
Bracket Notation Parsing (#6, #16)
Loading editor...
JSON String Escaping (#17)
Loading editor...
Email Validation (Basic)
Loading editor...
Quick Reference
| Pattern | Meaning |
|---|---|
. | Any character except \n (all with s flag) |
\d | Digit [0-9] |
\w | Word [a-zA-Z0-9_] |
\s | Whitespace |
\D, \W, \S | Negations |
[abc] | One of a, b, c |
[^abc] | NOT one of a, b, c |
+ | 1 or more |
* | 0 or more |
? | 0 or 1 |
{n} | Exactly n |
{n,} | n or more |
{n,m} | n to m |
^ | Start of string/line |
$ | End of string/line |
\b | Word boundary |
(x|y) | Alternation |
(x) | Capturing group |
(?:x) | Non-capturing group |
(?<name>x) | Named group |
x(?=y) | Lookahead |
(?<=y)x | Lookbehind |
Interview Tips
- Use literal syntax for static patterns —
/pattern/flagsis cleaner and more performant. - Use constructor for dynamic patterns —
new RegExp(variable, 'g'). - Remember that
gflag makestestandexecstateful — either avoidgfor simple checks or resetlastIndex. - Use
matchAllinstead ofexecloops — cleaner for iterating all matches with groups.