A regular expression, or regex, describes a pattern to find in text. In JavaScript, it can replace a long character-by-character check with a compact test, extract pieces of a string, or transform matching text. A ZIP code check, for example, can specify five digits, a hyphen, and four digits in one pattern. section 12.1 section 12.7
const isZipCode = (candidate: string) =>
/^\d{5}-\d{4}$/.test(candidate);
The anchors require the pattern to span the whole candidate; \d{5} and \d{4} require the two groups of digits. Without the anchors, finding the format somewhere inside a longer string would be enough. section 12.1 section 12.2.2
A pattern combines terms with operators. Ordinary characters match themselves in sequence; [abc] matches one character from a class; and a backslash escapes a character that otherwise has special meaning. Operators such as * and + repeat the preceding term, while ? makes it optional. Parentheses group terms and capture matched text by default. Flags change the search: i ignores case, and g continues beyond the first match. section 12.2.2 section 12.7
Write a fixed pattern as a slash-delimited literal, such as /test/. Use new RegExp("test") when the pattern must be assembled at runtime. Both create a RegExp instance, but a pattern inside a JavaScript string needs its backslashes escaped again: a literal backslash is easier to read in /\\/ than in new RegExp("\\\\"). Treat user-supplied patterns cautiously; some can consume substantial CPU time. section 12.2.1 section 12.2.2
Choose the string operation according to the result you need:
- Use match with a non-global pattern to obtain its full match and captures. With g, match instead returns full matches without their captures; use matchAll to iterate through global matches with captures. section 12.4.2
- Use replace with a regex to transform matching text. A replacer function receives the match and its captures, so /-([a-z])/g can turn each hyphen-plus-letter into an uppercase letter. section 12.5
Lookahead, written (?=pattern), checks text to the right without consuming it. This can select a name only when a specified word occurs later, or locate digits before groups of three for number formatting. The check does not become part of the matched text. section 12.6.1
Compact does not always mean suitable or fast. Greedy repetition first consumes as much as it can; if a later term fails, the engine backtracks and tries alternatives. Overlapping choices can make rejection extremely slow, including for an apparently simple roster pattern. Prefer a full parser when the string structure cannot be expressed as a reasonably sized regex, and examine performance before accepting arbitrary patterns. section 12.6.3 section 12.0































