Glossary / Regular expressions
Regular expressions
Regular expressions describe patterns for searching, matching, validating, splitting, and replacing strings. JavaScript offers literal syntax (/.../flags) and the RegExp constructor. Regex is powerful for local lexical patterns; nested or context-sensitive formats (such as full HTML or complex programming languages) need parsers with grammar-aware structure.
Syntax and state
Patterns support character classes, groups/captures, alternation, quantifiers, anchors, lookahead/lookbehind, and flags. Common flags include g (global), i (case-insensitive), m (multiline anchors), s (dot matches line terminators), u (Unicode-aware mode), y (sticky), and newer v Unicode-set mode where supported.
Global and sticky regexes are stateful: test and exec update lastIndex. Reusing the same regex can produce alternating or position-dependent results. Reset or clone when independent matching is intended. Unicode mode changes code-point handling for regex atoms, but does not make . match a whole grapheme cluster.
Performance and security
Backtracking patterns with ambiguous nested quantifiers can take exponential time on crafted input (ReDoS). Bound input size, avoid catastrophic forms, and use safe regex subsets/engines for attacker-controlled patterns. Escape user input before inserting it into a pattern; escaping for a regex is different from escaping for HTML or SQL. Validation patterns should be anchored when the entire input must match and should be tested against valid and adversarial cases.
Interview questions
- Why can
/x/g.test(value)alternate results? The global regex updateslastIndex. - What is catastrophic backtracking? Excessive exploration of ambiguous paths causing very slow matching.
- Does the Unicode flag count grapheme clusters? No, it changes code-point handling; segmentation APIs are needed for graphemes.
- How safely include user text in a regex? Escape it for regex syntax or avoid dynamic regex construction.