Introduction to Regex
A regular expression, or regex, is a pattern that describes a set of strings. JavaScript uses regular expressions to test whether a string has a certain form, to find the parts of a string that match, and to replace them. A pattern such as /^\d{4}$/ reads as the start of the string, then exactly four digits, then the end, which makes it a quick check for a PIN.
Regular expressions suit text with a clear pattern, such as dates, codes and repeated spaces. For structured formats such as HTML, JSON or full email addresses, a proper parser or a simpler check is usually more reliable.
Creating a regular expression
Section titled “Creating a regular expression”A regex literal is written between slashes, with any flags after the closing slash. The RegExp constructor builds one from a string, which is needed when the pattern is not known until the program runs. The test() method returns true or false.
const pin = /^\d{4}$/;
console.log(pin.test('2580'));console.log(pin.test('25800'));console.log(pin.test('25a0'));
const word = 'colour';const flexible = new RegExp(word.replace('ou', 'ou?'), 'i');console.log(flexible, flexible.test('COLOR'));This prints:
truefalsefalse/colou?r/i trueIn a string passed to RegExp, every backslash has to be doubled, so /\d+/ becomes new RegExp('\\d+').
Finding matches
Section titled “Finding matches”match() is a string method that searches with a regex. Without the g flag it returns the first match with its position, and with g it returns an array of every match. When nothing matches it returns null, not an empty array.
const receipt = 'Bread £1.45, milk £0.95, coffee £6.50';
console.log(receipt.match(/£\d+\.\d{2}/));console.log(receipt.match(/£\d+\.\d{2}/g));console.log(receipt.match(/£\d+\.\d{3}/g));This prints:
[ '£1.45', index: 6, input: 'Bread £1.45, milk £0.95, coffee £6.50', groups: undefined][ '£1.45', '£0.95', '£6.50' ]nullThe dot is escaped as \. because a plain . matches any character.
Capturing groups
Section titled “Capturing groups”Brackets around part of a pattern capture what that part matched. A group can also have a name, written (?<name>…), which is easier to read than a number. In replace(), $1 or $<name> inserts a group’s text.
const datePattern = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;const result = '2026-12-03'.match(datePattern);
console.log(result[0], result[1]);console.log(result.groups.day, result.groups.month, result.groups.year);console.log('2026-12-03'.replace(datePattern, '$<day>/$<month>/$<year>'));This prints:
2026-12-03 202603 12 202603/12/2026result[0] is the whole match and result[1] is the first group. To get the groups of every match in a string, use matchAll() with the g flag, which returns an iterator of match results.
const log = 'Order 17 shipped, order 23 delayed, order 41 shipped';
for (const match of log.matchAll(/order (\d+) (\w+)/gi)) { console.log(match[1], match[2]);}This prints:
17 shipped23 delayed41 shippedReplacing text
Section titled “Replacing text”replace() with a regex changes the first match, or every match with the g flag.
const note = 'Call me on Tuesday';console.log(note.replace(/\s+/g, ' '));console.log('grey, Grey, GREY'.replace(/grey/gi, 'gray'));console.log('a cat, a category, a scat'.match(/\bcat\b/g));This prints:
Call me on Tuesdaygray, gray, gray[ 'cat' ]\b marks a word boundary, so /\bcat\b/ finds cat only as a whole word. Find and Replace Methods covers replace() and replaceAll() in more detail.
Syntax reference
Section titled “Syntax reference”| Pattern | Matches |
|---|---|
. |
any character except a line break, or any character at all with the s flag |
\d \D |
a digit, which is the same as [0-9], and anything except a digit |
\w \W |
a word character, which is the same as [A-Za-z0-9_], and anything except one |
\s \S |
a whitespace character, such as a space, tab or line break, and anything except one |
[abc] |
any one of the characters listed |
[^abc] |
any one character that is not listed |
[a-z] |
any character in the range; ranges can be combined, as in [A-Za-z] |
^ $ |
the start and the end of the string, or of each line with the m flag |
\b \B |
a word boundary, and a position that is not one |
a|b |
either a or b |
(…) |
a capturing group |
(?<name>…) |
a named capturing group |
(?:…) |
a group that does not capture, used only to apply a quantifier or | to several characters |
\ |
an escape, which makes a special character such as . or ( match itself |
Quantifiers go after a character, a set or a group, and say how many times it may repeat:
| Quantifier | Repeats |
|---|---|
* |
zero or more times |
+ |
one or more times |
? |
zero times or once |
{3} |
exactly 3 times |
{2,5} |
from 2 to 5 times |
{2,} |
2 or more times |
There is no {,5} form in JavaScript. Without the u or v flag it is read as the literal characters {,5}, and with either flag it is a syntax error, so write {0,5} for at most five. Quantifiers are greedy, which means they match as much as they can, and a ? after one, as in +?, makes it match as little as it can.
| Flag | Effect |
|---|---|
g |
finds every match rather than stopping at the first |
i |
ignores the difference between capital and small letters |
m |
makes ^ and $ match at the start and end of each line |
s |
lets . match line breaks as well |
u |
treats the pattern as Unicode, so that an emoji counts as one character and \u{…} escapes work |
v |
an upgraded form of u, which adds set operations inside square brackets |
y |
sticky, which matches only at the position given by the regex’s lastIndex |
d |
records the start and end of each group in the match result’s indices |
A regex with the g or y flag remembers where its last match ended in lastIndex, so calling test() on it repeatedly with the same string can give different answers. Use a regex without those flags for simple checks.
regex101, with its flavour set to ECMAScript, explains each part of a pattern and shows what it matches as you type. The MDN regular expressions guide covers the full syntax.
Steve Griffith covers this topic in his video Intro to Regular Expressions.