Codiqo

Learn JavaScript · lesson 59 of 60 · about 10 minutes

Regular Expressions

Describe a pattern of text once, then test, find and replace it anywhere.

What you'll learn

  • Write simple patterns with \d, \w, + and character sets
  • Test text with test() and find matches with match()
  • Replace every match with replace() and the g flag

The sign-up form

Visitors can now sign up and post in the guestbook, and Sam checks what they type. A username has to be 3 to 12 letters, digits or underscores, so sam_codes gets Username ok: sam_codes and sam codes! gets Not a username: "sam codes!". And because people sometimes post their phone numbers, any run of 6 or more digits in a new message becomes [number hidden] before it goes up, with the extra spaces tidied away.

Patterns, not exact text

A regular expression (regex) describes a pattern of text. It's written between slashes, like /cat/.

A few building blocks go a long way:
- \d is any digit, \w any letter, digit or underscore, \s any space
- [aeiou] is any one of those characters
- + means one or more of the thing before it
- ^ and $ mean the start and end of the text

Testing text

const pin = /^\d\d\d\d$/;
console.log(pin.test("4096"));
console.log(pin.test("40a6"));
console.log(/cat/i.test("I love CATS"));

Output

true
false
true

Finding and replacing

text.match(/\d+/g) gives an array of every match (the g flag means global: find them all), or null if there are none. text.replace(/\s+/g, " ") replaces every match. The i flag ignores upper and lower case.

match and replace

const order = "3 teas, 12 cakes and 1 pie";
console.log(order.match(/\d+/g));

const messy = "too    many   spaces";
console.log(messy.replace(/\s+/g, " "));

Output

[ '3', '12', '1' ]
too many spaces

How many times

{3,12} after a piece of a pattern means between 3 and 12 of it, and {6,} means 6 or more. So /^\w{3,12}$/ is the whole text being 3 to 12 word characters, and /\d{6,}/g finds every run of at least 6 digits. The message goes through two replaces in a row: the long numbers first, then /\s+/g turns every run of spaces, tabs or new lines into one space, and trim() takes away any left at the ends.

Tip

Regexes are powerful but easy to get wrong. Test them on a few examples, including ones that should not match.

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.