A regular expression (regex) is a pattern that describes text. Instead of asking “does this string contain exactly cat?”, you can ask “does it contain a word that starts with a capital letter and ends with a number?”
Use cases you will meet:
- checking that an input looks like an email, a phone number or a postcode,
- finding or replacing patterns in text,
- pulling parts out of a string, such as the digits in
"Order #4521".
Creating a regex
Two ways. The literal form uses slashes:
const pattern = /cat/;
console.log(pattern.test("The cat sat")); // → true
console.log(pattern.test("The dog sat")); // → false
The constructor form takes a string. It is useful when the pattern is built at run time.
const word = "cat";
const pattern = new RegExp(word);
console.log(pattern.test("concatenate")); // → true
In the constructor form, backslashes in the string must be doubled: new RegExp("\\d+") is the same as /\d+/.
Your first useful pattern
const hasDigit = /\d/;
console.log(hasDigit.test("abc123")); // → true
console.log(hasDigit.test("abcdef")); // → false
\d means “any digit”. The next lessons build up the vocabulary: Patterns and Character Classes, Quantifiers and Groups and Flags.
A mini example: highlight digits
const text = "Order 42 shipped on day 7";
console.log(text.replace(/\d+/g, "#")); // → Order # shipped on day #
Do not fear them
Regex looks cryptic, but you only need a small part of it for most jobs. Learn it in small steps, test each pattern with a few examples (including ones that should not match), and write a short comment above any pattern that is not obvious.