SKU // 85

JavaScript RegExp

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.

// Writing a Pattern

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
true false false

test() is the simplest regex method: does the pattern appear anywhere in the text? Yes or no.

// A Taste of the Power

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)
true false false

// Where Regexes Get Used

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 elsenew string
str.split(regex)Break text wherever it matchesarray
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"]
6 ["42", "57"] Order # shipped. Order # pending. ["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.

// More First Examples

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
6 null Visit W3Schools! ["red", "green", "blue"] ["1", "0", "0"] ["1", "10", "10"]

Notice the second line: match returns null when nothing matches, and the pattern W3schools (lowercase s) does not match W3Schools.

W3Schools error
W3Schools' "Using String match()" example is exactly that second line: it searches "Visit W3Schools" for /W3schools/ with no i flag, so the result is null, not a match. Case matters unless you add i.

// Two Ways to Create a RegExp

// 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
Watch out
In the constructor, the pattern is a string, so every backslash must be doubled: /\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.

// Practical Example: Tidying Input

const phone = "(410) 555-0199";
const digitsOnly = phone.replace(/\D/g, "");   // \D = anything that is NOT a digit

console.log(digitsOnly);
4105550199

// How to Approach Regex

Tip
Build patterns a little at a time and test each step. Start with something that matches too much, then tighten it. Write a comment next to any regex explaining what it is for; even experienced developers struggle to read someone else's regex cold.

// Quick Check

What does this log?

console.log("Room 12, Room 7".match(/\d+/g));
Show answer
["12", "7"]. \d+ means one or more digits, and g collects every match.

What does "Hello".match(/hello/) return?

  1. ["Hello"]
  2. true
  3. null
  4. -1
Show answer
C. Without the i 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?

  1. /word/g
  2. /"word"/g
  3. new RegExp(word, "g")
  4. RegExp.word("g")
Show answer
C. A literal like /word/ searches for the letters w-o-r-d. When the pattern comes from a variable, use the constructor.

// Try It

  1. Click Open Playground and run it. Explain why the two results differ
  2. Use /^\d{5}$/ to check three zip codes, one valid and two not
  3. Pull every number out of a sentence with match(/\d+/g)
  4. Build a regex from a variable with new RegExp and use it to count a word in a paragraph
// Video Walkthroughs
Last updated: Oct 10, 2026, 1:46 AM ET