Regular expressions
A regular expression is a pattern that describes what the text you want looks like: "three digits in a row", "a word of Latin letters", "a string that looks like an email". It is used to validate input and to find and replace fragments. The syntax looks cryptic at first, but there are only a few basic symbols.
A pattern and the test method
A regular expression is written between two slashes. The test() method tells whether a string contains a match for the pattern:
const pattern = /cat/;
console.log(pattern.test('Our cat is asleep')); // trueA plain pattern of letters looks for exactly those letters in a row, like includes(). The power of regular expressions is in the special symbols.
Character classes and counts
Special symbols describe not a specific letter but a whole group. A number in curly braces or the + sign after a symbol sets how many times it repeats:
const zip = /^\d{5}$/;
console.log(zip.test('10115')); // true
console.log(zip.test('1011')); // falseThe ^ symbol means the start of the string, and $ its end: the whole pattern must match the whole string.
| Symbol | Meaning |
|---|---|
\d | any digit |
\w | a Latin letter, digit or _ |
\s | a whitespace character |
. | any character |
[abc] | one of the listed |
+ | once or more |
* | zero times or more |
{3} | exactly three times |
^ and $ | start and end of the string |
Flags
Flags are written after the closing slash — letters that change how the search works. The i flag ignores case, and g finds all matches, not just the first:
console.log(/hello/i.test('HELLO, world')); // trueFinding matches
The string method match() with the g flag returns an array of all the fragments found. If there are no matches, it returns null:
const text = 'Orders 12, 7 and 105';
const numbers = text.match(/\d+/g);
console.log(numbers.join(', ')); // 12, 7, 105Replacing by a pattern
replace() accepts a regular expression instead of a string. With the g flag every match is replaced:
const phone = '+1 (555) 123-4567';
console.log(phone.replace(/\D/g, '')); // 15551234567The capital \D is the opposite of \d: "any character except a digit". This strips everything extra from the number.
Groups
Parentheses mark a group in the pattern — a part of the match you can get separately. Without the g flag, match() returns an array where the groups follow the whole match:
const date = '2026-03-08';
const parts = date.match(/(\d{4})-(\d{2})-(\d{2})/);
console.log(parts[1]); // 2026
console.log(parts[3]); // 08Common mistake
The dot, plus, parentheses and some other signs are special symbols in a pattern. To find the character itself, put a backslash before it:
console.log(/a.c/.test('abc')); // true
console.log(/a\.c/.test('abc')); // false
console.log(/a\.c/.test('a.c')); // trueThe pattern /a.c/ matched abc because the dot means "any character". When you look for a dot in a website address or a price, write \..