RegExp
A regular expression — a pattern for finding and replacing text.
Available since: ES3
Syntax
new RegExp(pattern, flags)Parameters
| Parameter | Type | Description |
|---|---|---|
| pattern | string | The regular expression pattern. |
| flags | string | Optional. Flags: g, i, m, s, u, y, d, v. |
Return value
RegExpA regular expression object.
Examples
A literal between slashes:
const digits = /\d+/;
console.log(digits.test('Order 42'));Output:
trueA pattern from a string — when part of it comes from a variable:
const word = 'cat';
const regex = new RegExp(`\\b${word}\\b`, 'i');
console.log(regex.test('The Cat sleeps'));
console.log(regex.source);Output:
true
\bcat\bThe basic symbols:
console.log('a1 b22 c'.match(/\d/g).join(','));
console.log('hello world'.match(/\w+/g).join(','));
console.log('2026-03-15'.replace(/(\d+)-(\d+)-(\d+)/, '$3.$2.$1'));Output:
1,2,2
hello,world
15.03.2026Notes
Frequently needed symbols: \d is a digit, \w a letter, digit or underscore, \s whitespace, . any character, + one or more times, * zero or more, ? optional, ^ and $ the start and end of the string, parentheses a group.
In a string for new RegExp() the backslash must be doubled: '\\d+'. The literal /\d+/ does not need it.
See also
- RegExp.prototype.test — Checks whether a string matches a pattern.
- RegExp flags — Flags change how matching works: g for all matches, i for case-insensitive, and more.
- String.prototype.match — Finds matches of a regular expression.
- String.prototype.replace — Replaces the first match (or all of them with a regex g flag).
In the tutorial
- Regular expressions — Regular expressions in JavaScript for beginners: patterns, flags, character classes, testing, finding and replacing text.