JavaScript Regex Cheat Sheet
Quick-reference for JavaScript regular expressions organized by method. Each section shows RegExp or String API usage with practical examples.
Quick Syntax Reference
Regex literal syntax and the RegExp constructor. Character classes, quantifiers, and anchors shown as JS literals.
const literal = /\d+/g;
const constructed = new RegExp('\\d+', 'g');
typeof literal // => 'object'
literal instanceof RegExp // => truePrefer literals for static patterns. Use the constructor when building patterns from variables.
// \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// * 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 boundaryRegExp.test() and RegExp.exec()
test() returns a boolean. exec() returns a full match object or null.
/^\d{5}$/.test('90210') // => true
/^\d{5}$/.test('9021') // => false
/^\d{5}$/.test('90210-12') // => falseconst 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)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 => 0With 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.
'price: $42.99'.match(/(\$)(\d+\.\d{2})/)
// => ['$42.99', '$', '42.99']
// .index => 7'a1 b2 c3'.match(/\d/g)
// => ['1', '2', '3']With /g, match() returns only matched strings. Groups and indices are discarded.
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 // => 3for (const [full, month, day] of text.matchAll(/(\w+) (\d+)/g)) {
console.log(`${month} ${day}`);
}
// Jan 5
// Feb 14
// Mar 21String.replace() and String.replaceAll()
Regex-powered replacement with capture group references and callback functions.
'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''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.
'price: 10 usd, tax: 2 usd'.replace(/\d+/g, (n) => {
return (Number(n) * 100).toString();
});
// => 'price: 1000 usd, tax: 200 usd''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.
'hello 42 world'.search(/\d+/) // => 6
'no numbers here'.search(/\d+/) // => -1search() always starts from the beginning. It ignores /g and lastIndex.
'one, two; three'.split(/[,;]\s*/)
// => ['one', 'two', 'three']
'camelCaseWords'.split(/(?=[A-Z])/)
// => ['camel', 'Case', 'Words']'a1b2c3'.split(/(\d)/)
// => ['a', '1', 'b', '2', 'c', '3', '']Capture Groups and Named Groups
Parentheses capture subpatterns. Named groups attach labels accessible via .groups.
const m = 'rgb(255, 128, 0)'.match(/rgb\((\d+), (\d+), (\d+)\)/);
m[1] // => '255'
m[2] // => '128'
m[3] // => '0'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'// 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.
'100px 200em 50px'.match(/\d+(?=px)/g)
// => ['100', '50'] (digits followed by "px")'100px 200em 50px'.match(/\d+(?!px)(?!\d)/g)
// => ['200'] (digits NOT followed by "px")'price: $42, cost: $18'.match(/(?<=\$)\d+/g)
// => ['42', '18'] (digits preceded by "$")'$42 18 $7'.match(/(?<!\$)\b\d+\b/g)
// => ['18'] (digits NOT preceded by "$")// 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.
// 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)const text = 'line1\nline2\nline3';
text.match(/^\w+/g) // => ['line1'] (^ = start of string)
text.match(/^\w+/gm) // => ['line1', 'line2', 'line3'] (^ = start of line)// 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') // => falseThe v flag supersedes u. It enables set subtraction (--) and intersection (&&) inside character classes.
const re = /test/gi;
re.flags // => 'gi'
re.global // => true
re.ignoreCase // => true
re.multiline // => falseCommon Practical Patterns
Everyday extraction patterns using JS string and RegExp methods.
const text = 'Contact alice@example.com or bob@test.org';
const emails = text.match(/[\w.+-]+@[\w-]+\.[\w.]+/g);
// => ['alice@example.com', 'bob@test.org']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']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'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
}Can you write this from memory?
Check if string `item_text` matches the pattern `/abc/`.