Encodera

Thanks for reading!

Donate to the site — we work hard for you.

JavaScript reference

RegExp

A regular expression — a pattern for finding and replacing text.

Available since: ES3

Syntax

new RegExp(pattern, flags)

Parameters

ParameterTypeDescription
patternstringThe regular expression pattern.
flagsstringOptional. 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:

true

A 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\b

The 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.2026

Notes

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

In the tutorial

  • Regular expressions — Regular expressions in JavaScript for beginners: patterns, flags, character classes, testing, finding and replacing text.

Thanks for reading!

Donate to the site — we work hard for you.