Regular Expressions — JavaScript

A regex is a pattern for finding text, written between slashes: /pattern/flags. Inside a pattern, \d means one digit, \S one character that is not a space, \…

A sign-up form asks for an email. One person types budi, another types budi@, and another [email protected]. Only the last one is right. Checking with includes('@') is not enough, because budi@ is accepted too. You need a way to tell JavaScript: "something, then @, then something, then a dot, then something".

That way is a regular expression (regex for short): a pattern for finding text. A pattern can be an exact word, but it can also be "any number" or "something, then @, then something". Regex is used for three things: to check a format (an email, for example), to take parts out of a text, and to replace text.

A first pattern: get every number

This example takes every number out of a sentence:

const text = 'Budi paid $50, Siti paid $75'
const numbers = text.match(/\d+/g)
console.log(numbers) // ['50', '75']

If nothing matches at all, match returns null, not an empty array. To always get an array, write text.match(/\d+/g) || []. The || uses [] when the left side is null.

Pattern pieces you will use a lot

Any other character matches itself, for example @ or the letters of budi.

Checking for a match with test()

This example uses test() for two jobs: to look for a digit, then to check the format of an email:

console.log(/\d/.test('abc123')) // true

const emailPattern = /\S+@\S+\.\S+/
console.log(emailPattern.test('[email protected]')) // true
console.log(emailPattern.test('budi'))          // false

pattern.test(text) only answers whether something matches: true or false. The first line gives true because abc123 has a digit. Read the email pattern from the left:

budi has no @ and no dot, so the result is false.

emailPattern searches anywhere in the text, so emailPattern.test('my name is [email protected] ok') is also true. To check the whole content of an input box, such as an email or a postal code, add ^ (start of the text) before the pattern and $ (end of the text) after it. Then the whole text must match:

const wholeEmail = /^\S+@\S+\.\S+$/
console.log(wholeEmail.test('[email protected]'))            // true
console.log(wholeEmail.test('my name is [email protected]')) // false

const postCode = /^\d{5}$/
console.log(postCode.test('12345'))  // true
console.log(postCode.test('1234a'))  // false

postCode checks a postal code: \d{5} means exactly 5 digits, and ^ and $ allow nothing before or after them. '1234a' fails because a is not a digit.

Other options for checking an email address:

Way When to use it
<input type="email"> The easiest: the browser itself checks the format before the form is sent.
A regex with ^ and $ The way used in this lesson: checking it yourself in JavaScript, for example while the user types.
A check on the server, then a confirmation email The only way to be sure the address really exists. Even the text @@@.@ passes the regex above.

Notice which side makes the call: test is called on the pattern (pattern.test(text)), while match and replace are called on the text (text.match(pattern)).

The g and i flags

text.replace(pattern, replacement) returns a new text with the matching part replaced. Without g, only the first match is replaced:

console.log('a-a-a'.replace(/a/, 'X'))  // X-a-a
console.log('a-a-a'.replace(/a/g, 'X')) // X-X-X
console.log(/budi/i.test('BUDI'))       // true

The i flag treats capital and small letters as the same. That is why the third line gives true, and why /a/i matches both a and A. Flags go after the closing slash, and you can combine them: /a/gi.

⚠️ Patterns that look right but miss

TL;DR: A regex is a pattern for finding text, written between slashes: /pattern/flags. Inside a pattern, \d means one digit, \S one character that is not a space, \. a dot, and + one or more of what comes before it. pattern.test(text) answers true or false. text.match(/pattern/g) gets every match, or null when there is none, so add || [] to always get an array. text.replace(pattern, newText) replaces the matching part. A flag is a setting letter after the closing slash: g means every match, and i treats capital and small letters as the same.

⚡ A pattern between slashes

Write:

const text = 'Budi paid $50, Siti paid $75'
text.match(/\d+/g) // ['50', '75']
Guess first: if there are no numbers at all, what does match return?

null, not an empty array. To always get an array, write text.match(/\d+/g) || []: the || uses [] when the left side is null.

Meaning: /\d+/g is a regex: a pattern for finding text, written between slashes. \d means one digit and + means one or more, so 50 is matched as a whole. The g after the closing slash is a flag (an extra setting): find every match, not only the first one. match returns every match in an array.

⚡ Check a format with test()

Write:

const emailPattern = /\S+@\S+\.\S+/
emailPattern.test('[email protected]') // true
emailPattern.test('budi')          // false

Meaning: pattern.test(text) only answers true or false: a match or no match. In this pattern, \S+ means one or more characters that are not spaces, and \. means a dot, because . on its own means any character. So the pattern reads: something, @, something, a dot, something. budi has no @ and no dot, so the result is false.

⚡ The g and i flags

Write:

'a-a-a'.replace(/a/, 'X')  // X-a-a
'a-a-a'.replace(/a/g, 'X') // X-X-X
/budi/i.test('BUDI')       // true

Meaning: replace finds the part of the text that matches the pattern and replaces it with 'X'. Without the g flag, replace only replaces the first match. The i flag treats capital and small letters as the same. That is why the third line gives true, and why /a/i matches both a and A. Flags can be combined: /a/gi.

What you will learn