Regex in JavaScript

JavaScript RegExp syntax, APIs, flags, named captures, and high-value browser/Node recipes.

View
StandardDetailedCompact
Export
Copy the compact sheet, download it, or print it.
Download
`D` dense toggle · `C` copy all

JavaScript Regex APIs

Core JavaScript regex syntax and methods.

Regex literal

Declare a regex using JavaScript literal syntax.

javascriptANYjavascriptsyntaxliteral
javascript
/error/i
Notes

Fast and readable when the pattern is static.

RegExp constructor

Build a regex dynamically from strings.

javascriptANYjavascriptsyntaxconstructor
javascript
new RegExp("^" + prefix + "\\d+$", "i")
Notes

Useful when the pattern is assembled at runtime.

test() boolean match

Check whether a regex matches a string.

javascriptANYjavascriptapitest
javascript
/error/i.test(message)
Notes

Returns `true` or `false`.

exec() detailed match

Get captures and index information from a match.

javascriptANYjavascriptapiexec
javascript
/(\d{4})-(\d{2})-(\d{2})/.exec(dateStr)
Notes

Returns an array-like match object or `null`.

String.match()

Match against a string and return results.

javascriptANYjavascriptapimatch
javascript
text.match(/\b\w+\b/g)
Notes

With `g`, returns all matches; without `g`, returns the first detailed match.

String.matchAll()

Iterate all matches with captures.

javascriptANYjavascriptapimatchall
javascript
Array.from(text.matchAll(/(?<key>\w+)=(?<val>\w+)/g))
Notes

Useful when you need every match and capture groups.

String.replace()

Replace matched text using a regex.

javascriptANYjavascriptapireplace
javascript
text.replace(/\s+/g, " ")
Notes

Common for cleanup and normalization.

replace() callback

Compute replacements dynamically from captures.

javascriptANYjavascriptapireplace
javascript
text.replace(/(\w+),\s*(\w+)/g, (_, last, first) => `${first} ${last}`)
Notes

Useful for reformatting structured text.

String.split() with regex

Split a string using a regex delimiter.

javascriptANYjavascriptapisplit
javascript
csvLine.split(/\s*,\s*/)
Notes

Removes optional whitespace around commas.

JavaScript Flags and Captures

Flags, named captures, and replacement patterns in JavaScript.

Common JS flags

Global, ignore-case, multiline, dotAll, Unicode, sticky, indices.

javascriptANYjavascriptflags
javascript
/pattern/gimsuyd
Notes

JavaScript supports several flags; combine only the ones you need.

Named capture group

Capture with a descriptive group name.

javascriptANYjavascriptcapturesnamed
javascript
/(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/
Notes

Read captures using `match.groups.year` in modern runtimes.

Named backreference in JS

Backreference a named capture.

javascriptANYjavascriptbackreferencenamed
javascript
/(?<q>["\']).*?\k<q>/
Notes

Useful for matching paired quotes.

Replacement with numbered groups

Use `$1`, `$2`, etc. in replacement strings.

javascriptANYjavascriptreplacecaptures
javascript
text.replace(/(\w+)\s+(\w+)/, "$2, $1")
Notes

Convenient for simple reordering.

Replacement with named groups

Use a replacement callback to access named captures clearly.

javascriptANYjavascriptreplacenamed
javascript
text.replace(/(?<h>\d{2}):(?<m>\d{2})/, (...args) => { const groups = args.at(-1); return `${groups.h}h ${groups.m}m`; })
Notes

Named groups improve readability in larger replacements.

Unicode property escapes

Match Unicode letters or scripts in JS.

javascriptANYjavascriptunicode
javascript
/^\p{L}+$/u
Notes

Requires the `u` flag.

JavaScript Recipes

High-value browser and Node regex recipes.

Basic email shape

Check a simple email-like structure.

javascriptANYjavascriptvalidationemail
javascript
/^[^\s@]+@[^\s@]+\.[^\s@]+$/
Notes

A lightweight client-side check, not a full RFC parser.

Slug validator

Match lowercase slugs with hyphens.

javascriptANYjavascriptvalidationslug
javascript
/^[a-z0-9]+(?:-[a-z0-9]+)*$/
Notes

Good for URLs, IDs, and content slugs.

Key=value extractor

Extract query-like key-value pairs.

javascriptANYjavascriptparsingquerystring
javascript
/([^&=?#]+)=([^&=#]*)/g
Notes

Use `matchAll` to iterate all pairs.

Collapse internal whitespace

Normalize repeated whitespace down to single spaces.

javascriptANYjavascriptcleanupwhitespace
javascript
text.trim().replace(/\s+/g, " ")
Notes

Very common cleanup recipe.

Redact bearer token

Mask bearer tokens in logs.

javascriptANYjavascriptsecurityredaction
javascript
text.replace(/\bBearer\s+[A-Za-z0-9._-]+\b/g, "Bearer [REDACTED]")
Notes

Useful when sanitizing output.

Find hex colors

Extract CSS-like hex color literals.

javascriptANYjavascriptcssparsing
javascript
/#(?:[0-9A-Fa-f]{3}|[0-9A-Fa-f]{6}|[0-9A-Fa-f]{8})\b/g
Notes

Covers 3, 6, and 8 digit forms.

Basic semver parser

Extract version parts from a semantic version string.

javascriptANYjavascriptversionssemver
javascript
/^(?<major>0|[1-9]\d*)\.(?<minor>0|[1-9]\d*)\.(?<patch>0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/
Notes

Handy for tooling and validation.

Recommended next

No recommendations yet.