A regular expression (RegExp, or "regex") is a pattern that describes text. Instead of searching for one exact word, you can search for "any 5 digits," "anything that looks like an email," or "every word starting with a capital letter." They look cryptic at first, but they are built from a small set of pieces, and this section teaches them one at a time.
A regex is written between forward slashes. Letters and numbers match themselves:
const pattern = /cat/;
pattern.test("concatenate") // true ("cat" appears inside)
pattern.test("Cat") // false (case matters)
pattern.test("dog") // false
test() is the simplest regex method: does the pattern appear anywhere in the text? Yes or no.
Special symbols describe kinds of characters and how many of them. A preview of what the rest of this section covers:
/\d/ // any digit
/\d{5}/ // exactly 5 digits in a row
/^\d{5}$/ // the WHOLE text is exactly 5 digits (a US zip code)
/colou?r/ // "color" or "colour" (the u is optional)
/cat|dog/ // "cat" or "dog"
/hello/i // "hello" ignoring case (the i after the slash is a flag)
const zip = /^\d{5}$/;
zip.test("21201") // true
zip.test("2120") // false (only 4)
zip.test("21201a") // false (extra character)
You already met some of these string methods in String Search. They all accept a regex:
| Method | Question | Returns |
|---|---|---|
| regex.test(str) | Does it match? | true / false |
| str.search(regex) | Where is the first match? | position or -1 |
| str.match(regex) | What matched? | array or null |
| str.replace(regex, new) | Swap matches for something else | new string |
| str.split(regex) | Break text wherever it matches | array |
const msg = "Order 42 shipped. Order 57 pending.";
msg.search(/\d/) // 6
msg.match(/\d+/g) // ["42", "57"]
msg.replace(/\d+/g, "#") // "Order # shipped. Order # pending."
"a, b,c , d".split(/\s*,\s*/) // ["a", "b", "c", "d"]
That last one splits on a comma with any amount of space around it, something a plain string separator cannot do.
The letter after the closing slash is called a flag (W3Schools also calls it a modifier): /pattern/flags. Here are the three string methods with the i (ignore case) flag, plus a first look at the pieces the next lessons cover:
const text = "Visit W3Schools";
console.log(text.search(/w3schools/i)); // position of the match
console.log(text.match(/W3schools/)); // no i flag, and the case differs
console.log("Visit Microsoft!".replace(/microsoft/i, "W3Schools"));
console.log("Black, white, red, green, blue".match(/red|green|blue/g)); // | means OR
console.log("Give 100%!".match(/\d/g)); // \d = any digit
console.log("1, 100 or 1000?".match(/10?/g)); // ? = the 0 is optional
Notice the second line: match returns null when nothing matches, and the pattern W3schools (lowercase s) does not match W3Schools.
"Visit W3Schools" for /W3schools/ with no i flag, so the result is null, not a match. Case matters unless you add i.
// 1. Literal: use when you know the pattern while writing code
const a = /\d+/g;
// 2. Constructor: use when the pattern comes from a variable
const word = "apple";
const b = new RegExp(word, "gi"); // same as /apple/gi
/\d+/ becomes new RegExp("\\d+"). Forgetting this is the number one constructor bug, and nothing warns you: new RegExp("\d+") quietly becomes /d+/, which matches the letter d.
const phone = "(410) 555-0199";
const digitsOnly = phone.replace(/\D/g, ""); // \D = anything that is NOT a digit
console.log(digitsOnly);
What does this log?
console.log("Room 12, Room 7".match(/\d+/g));
["12", "7"]. \d+ means one or more digits, and g collects every match.What does "Hello".match(/hello/) return?
["Hello"]truenull-1i flag, case matters, so there is no match, and match returns null. (search is the one that returns -1.)A user types a word into a box and you want to search for it. Which creates the regex?
/word/g/"word"/gnew RegExp(word, "g")RegExp.word("g")/word/ searches for the letters w-o-r-d. When the pattern comes from a variable, use the constructor./^\d{5}$/ to check three zip codes, one valid and two notmatch(/\d+/g)new RegExp and use it to count a word in a paragraph