Syntax Cache
BlogMethodFeaturesHow It WorksBuild a Game
  1. Home
  2. Cheat Sheets
  3. JavaScript
  4. JavaScript Regex Cheat Sheet
JavaScriptCheat Sheet

JavaScript Regex Cheat Sheet

Quick-reference for JavaScript regular expressions organized by method. Each section shows RegExp or String API usage with practical examples.

On this page
  1. 1Quick Syntax Reference
  2. 2RegExp.test() and RegExp.exec()
  3. 3String.match() and String.matchAll()
  4. 4String.replace() and String.replaceAll()
  5. 5String.search() and String.split()
  6. 6Capture Groups and Named Groups
  7. 7Lookahead, Lookbehind, and Non-Capturing Groups
  8. 8Flags
  9. 9Common Practical Patterns
Quick Syntax ReferenceRegExp.test() and RegExp.exec()String.match() and String.matchAll()String.replace() and String.replaceAll()String.search() and String.split()Capture Groups and Named GroupsLookahead, Lookbehind, and Non-Capturing GroupsFlagsCommon Practical Patterns

Quick Syntax Reference

Regex literal syntax and the RegExp constructor. Character classes, quantifiers, and anchors shown as JS literals.

Literal vs constructor
const literal = /\d+/g;
const constructed = new RegExp('\\d+', 'g');

typeof literal   // => 'object'
literal instanceof RegExp  // => true

Prefer literals for static patterns. Use the constructor when building patterns from variables.

Character classes
// \d  digit          \D  non-digit
// \w  word char      \W  non-word
// \s  whitespace     \S  non-whitespace
// .   any char (except newline without s flag)
// [abc]  set          [^abc]  negated set
// [a-z]  range        [A-Za-z0-9_]  same as \w
Quantifiers and anchors
// *   zero or more      +   one or more
// ?   zero or one       {3}  exactly 3
// {2,5}  2 to 5         {2,}  2 or more
// ^   start of string   $   end of string
// \b  word boundary     \B  non-word boundary

RegExp.test() and RegExp.exec()

test() returns a boolean. exec() returns a full match object or null.

test() — boolean match check
/^\d{5}$/.test('90210')    // => true
/^\d{5}$/.test('9021')     // => false
/^\d{5}$/.test('90210-12') // => false
exec() — match details
const re = /(\d{4})-(\d{2})-(\d{2})/;
const m = re.exec('Date: 2026-02-23');

m[0]       // => '2026-02-23'  (full match)
m[1]       // => '2026'        (group 1)
m[2]       // => '02'          (group 2)
m.index    // => 6             (match position)
exec() with /g — stateful iteration
const re = /\d+/g;
const str = 'a1 b22 c333';

re.exec(str)  // => ['1'],   re.lastIndex => 2
re.exec(str)  // => ['22'],  re.lastIndex => 6
re.exec(str)  // => ['333'], re.lastIndex => 11
re.exec(str)  // => null,    re.lastIndex => 0

With the /g flag, exec() advances lastIndex after each call. Reset it manually or create a fresh regex to restart.

String.match() and String.matchAll()

match() returns an array of matches. matchAll() returns an iterator of full match objects.

match() without /g — single match with groups
'price: $42.99'.match(/(\$)(\d+\.\d{2})/)
// => ['$42.99', '$', '42.99']
// .index => 7
match() with /g — all matches, no groups
'a1 b2 c3'.match(/\d/g)
// => ['1', '2', '3']

With /g, match() returns only matched strings. Groups and indices are discarded.

matchAll() — iterator with full details
const text = 'Jan 5, Feb 14, Mar 21';
const matches = [...text.matchAll(/(\w+) (\d+)/g)];

matches[0][0]  // => 'Jan 5'   (full match)
matches[0][1]  // => 'Jan'     (group 1)
matches[0][2]  // => '5'       (group 2)
matches.length // => 3
Destructure matchAll results
for (const [full, month, day] of text.matchAll(/(\w+) (\d+)/g)) {
  console.log(`${month} ${day}`);
}
// Jan 5
// Feb 14
// Mar 21

String.replace() and String.replaceAll()

Regex-powered replacement with capture group references and callback functions.

replace() with regex
'2026-02-23'.replace(/(\d{4})-(\d{2})-(\d{2})/, '$2/$3/$1')
// => '02/23/2026'

'hello world'.replace(/\b\w/g, c => c.toUpperCase())
// => 'Hello World'
replaceAll() — every match
'foo_bar_baz'.replaceAll('_', '-')  // => 'foo-bar-baz'

// With regex (must include /g flag):
'a1b2c3'.replaceAll(/\d/g, '#')  // => 'a#b#c#'

replaceAll() with a regex throws TypeError if the /g flag is missing.

Callback replacement
'price: 10 usd, tax: 2 usd'.replace(/\d+/g, (n) => {
  return (Number(n) * 100).toString();
});
// => 'price: 1000 usd, tax: 200 usd'
Named group references in replacement
'John Smith'.replace(/(?<first>\w+) (?<last>\w+)/, '$<last>, $<first>')
// => 'Smith, John'

String.search() and String.split()

search() returns the index of the first match. split() uses a regex delimiter.

search() — find match index
'hello 42 world'.search(/\d+/)   // => 6
'no numbers here'.search(/\d+/)  // => -1

search() always starts from the beginning. It ignores /g and lastIndex.

split() with regex
'one, two;  three'.split(/[,;]\s*/)
// => ['one', 'two', 'three']

'camelCaseWords'.split(/(?=[A-Z])/)
// => ['camel', 'Case', 'Words']
split() with capture group keeps delimiters
'a1b2c3'.split(/(\d)/)
// => ['a', '1', 'b', '2', 'c', '3', '']

Capture Groups and Named Groups

Parentheses capture subpatterns. Named groups attach labels accessible via .groups.

Numbered groups
const m = 'rgb(255, 128, 0)'.match(/rgb\((\d+), (\d+), (\d+)\)/);
m[1]  // => '255'
m[2]  // => '128'
m[3]  // => '0'
Named groups with (?<name>...)
const re = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;
const { groups } = '2026-02-23'.match(re);

groups.year   // => '2026'
groups.month  // => '02'
groups.day    // => '23'
$1 and $<name> in replacements
// Numbered reference
'2026-02-23'.replace(/(\d{4})-(\d{2})-(\d{2})/, '$3/$2/$1')
// => '23/02/2026'

// Named reference
'2026-02-23'.replace(
  /(?<y>\d{4})-(?<m>\d{2})-(?<d>\d{2})/,
  '$<d>/$<m>/$<y>'
)
// => '23/02/2026'

Lookahead, Lookbehind, and Non-Capturing Groups

Assertions match positions without consuming characters. Non-capturing groups organize patterns without creating captures.

Positive lookahead (?=...)
'100px 200em 50px'.match(/\d+(?=px)/g)
// => ['100', '50']  (digits followed by "px")
Negative lookahead (?!...)
'100px 200em 50px'.match(/\d+(?!px)(?!\d)/g)
// => ['200']  (digits NOT followed by "px")
Positive lookbehind (?<=...)
'price: $42, cost: $18'.match(/(?<=\$)\d+/g)
// => ['42', '18']  (digits preceded by "$")
Negative lookbehind (?<!...)
'$42 18 $7'.match(/(?<!\$)\b\d+\b/g)
// => ['18']  (digits NOT preceded by "$")
Non-capturing group (?:...)
// Groups without creating a capture
'foobar foobaz'.match(/foo(?:bar|baz)/g)
// => ['foobar', 'foobaz']

// Useful for alternation without polluting groups
const [, protocol] = 'https://example.com'.match(/^(https?):\/\/(?:www\.)?(.+)/);
protocol  // => 'https'

Flags

Flags modify how the regex engine interprets the pattern.

Common flags
// g  global — find all matches (not just first)
// i  ignoreCase — case-insensitive matching
// m  multiline — ^ and $ match line boundaries
// s  dotAll — . matches newline characters
// u  unicode — treat pattern as Unicode code points
// v  unicodeSets — ES2024, extends u with set notation

/hello/i.test('Hello World')  // => true
'a\nb'.match(/a.b/s)          // => ['a\nb']  (. matches \n)
Multiline flag
const text = 'line1\nline2\nline3';

text.match(/^\w+/g)   // => ['line1']  (^ = start of string)
text.match(/^\w+/gm)  // => ['line1', 'line2', 'line3']  (^ = start of line)
v flag — unicodeSets (ES2024)
// Set subtraction: match Greek letters except sigma
/[\p{Script=Greek}--[\u03C3]]/v.test('\u03B1')  // => true  (alpha)
/[\p{Script=Greek}--[\u03C3]]/v.test('\u03C3')  // => false (sigma)

// Set intersection
/[\p{Letter}&&\p{ASCII}]/v.test('a')  // => true
/[\p{Letter}&&\p{ASCII}]/v.test('\u00E9')  // => false

The v flag supersedes u. It enables set subtraction (--) and intersection (&&) inside character classes.

Check flags on a regex
const re = /test/gi;
re.flags       // => 'gi'
re.global      // => true
re.ignoreCase  // => true
re.multiline   // => false

Common Practical Patterns

Everyday extraction patterns using JS string and RegExp methods.

Email extraction
const text = 'Contact alice@example.com or bob@test.org';
const emails = text.match(/[\w.+-]+@[\w-]+\.[\w.]+/g);
// => ['alice@example.com', 'bob@test.org']
URL extraction
const text = 'Visit https://example.com/path?q=1 for info';
const urls = text.match(/https?:\/\/[\w.-]+(?:\/[\w./?&=%#-]*)?/g);
// => ['https://example.com/path?q=1']
Phone number normalization
function normalizePhone(phone) {
  const digits = phone.replace(/\D/g, '');
  return digits.replace(/(\d{3})(\d{3})(\d{4})/, '($1) $2-$3');
}

normalizePhone('555.123.4567')   // => '(555) 123-4567'
normalizePhone('555-123-4567')   // => '(555) 123-4567'
Date parsing with named groups
const dateStr = 'Event on 02/23/2026 at noon';
const m = dateStr.match(/(?<month>\d{2})\/(?<day>\d{2})\/(?<year>\d{4})/);

if (m) {
  const { year, month, day } = m.groups;
  new Date(`${year}-${month}-${day}`);
  // => 2026-02-23T00:00:00.000Z
}
Learn JavaScript in Depth
JavaScript String Methods Practice →
Warm-up1 / 1

Can you write this from memory?

Check if string `item_text` matches the pattern `/abc/`.

See Also
String Methods →ES6+ Features →

Start Practicing JavaScript

Free daily exercises with spaced repetition. No credit card required.

← Back to JavaScript Syntax Practice
Syntax Cache

Build syntax muscle memory with spaced repetition.

Product

  • Pricing
  • Our Method
  • Daily Practice
  • Design Patterns
  • Interview Prep

Resources

  • Blog
  • Compare
  • Cheat Sheets
  • Vibe Coding
  • Muscle Memory

Languages

  • Python
  • JavaScript
  • TypeScript
  • Rust
  • SQL
  • GDScript

Legal

  • Terms
  • Privacy
  • Contact

© 2026 Syntax Cache

Cancel anytime in 2 clicks. Keep access until the end of your billing period.

No refunds for partial billing periods.