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
Regex literal
/error/i

# Declare a regex using JavaScript literal syntax.

RegExp constructor
new RegExp("^" + prefix + "\\d+$", "i")

# Build a regex dynamically from strings.

test() boolean match
/error/i.test(message)

# Check whether a regex matches a string.

exec() detailed match
/(\d{4})-(\d{2})-(\d{2})/.exec(dateStr)

# Get captures and index information from a match.

String.match()
text.match(/\b\w+\b/g)

# Match against a string and return results.

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

# Iterate all matches with captures.

String.replace()
text.replace(/\s+/g, " ")

# Replace matched text using a regex.

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

# Compute replacements dynamically from captures.

String.split() with regex
csvLine.split(/\s*,\s*/)

# Split a string using a regex delimiter.

## JavaScript Flags and Captures
Common JS flags
/pattern/gimsuyd

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

Named capture group
/(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/

# Capture with a descriptive group name.

Named backreference in JS
/(?<q>["\']).*?\k<q>/

# Backreference a named capture.

Replacement with numbered groups
text.replace(/(\w+)\s+(\w+)/, "$2, $1")

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

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

# Use a replacement callback to access named captures clearly.

Unicode property escapes
/^\p{L}+$/u

# Match Unicode letters or scripts in JS.

## JavaScript Recipes
Basic email shape
/^[^\s@]+@[^\s@]+\.[^\s@]+$/

# Check a simple email-like structure.

Slug validator
/^[a-z0-9]+(?:-[a-z0-9]+)*$/

# Match lowercase slugs with hyphens.

Key=value extractor
/([^&=?#]+)=([^&=#]*)/g

# Extract query-like key-value pairs.

Collapse internal whitespace
text.trim().replace(/\s+/g, " ")

# Normalize repeated whitespace down to single spaces.

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

# Mask bearer tokens in logs.

Find hex colors
/#(?:[0-9A-Fa-f]{3}|[0-9A-Fa-f]{6}|[0-9A-Fa-f]{8})\b/g

# Extract CSS-like hex color literals.

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

# Extract version parts from a semantic version string.

Recommended next

No recommendations yet.