Two ways to create a regex
JavaScript has two regex syntaxes:
- Literal:
/pattern/flags— written between slashes, parsed at definition time. Faster, can't have embedded variables. - Constructor:
new RegExp('pattern', 'flags')— a function call. Slower, but you can interpolate variables.
Use the literal form whenever the pattern is fixed. Use the constructor only when you need to build the pattern dynamically.
The methods
JavaScript splits regex methods between RegExp objects and String:
regex.test(str)— boolean: does it match?regex.exec(str)— first match (or with /g flag, iterates).str.match(regex)— first match, or all matches with /g flag.str.matchAll(regex)— iterator of all matches (requires /g).str.replace(regex, replacement)— replace first (or all with /g).str.replaceAll(regex, replacement)— replace all (regex must have /g).str.split(regex)— split.str.search(regex)— index of first match, -1 if not found.
Quirks worth knowing
The /g flag is stateful. A regex with /g remembers lastIndex across exec calls. This causes "my regex matches the first time but not the second" bugs. matchAll is the modern, safer alternative.
Backslashes in constructor strings need doubling. new RegExp('\\d+'), not '\d+'. Same problem as Python without raw strings — and JavaScript has no raw string equivalent for regex.