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']
/\d+/gis the regex. The slashes/at the front and back hold the pattern between them, with no quote marks. This form is called a regex literal.\dmeans one digit, from 0 to 9.+means "one or more" of whatever comes right before it. So\d+matches50as a whole, not5and0separately.- The
gafter the closing slash is a flag (an extra setting).gmeans global: find every match, not only the first one. - With the
gflag,text.match(pattern)returns an array of every part that matched. Each item in that array is a string, not a number.
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
\done digit.[0-9]means the same: one character from the list inside the square brackets.\wone letter, digit or underscore.\sone space (tabs and line breaks count too).\S, with a capital S, is the opposite: one character of any kind that is not a space..one character of any kind. Need the dot character itself? Write\., with a backslash in front.- These three signs set how many of the thing right before them:
+one or more,*zero or more,?one or none.
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:
\S+: one or more characters that are not spaces (the name before the @),@: the @ sign itself,\S+again (the domain name after the @),\.: one dot,\S+(for examplecom).
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
- Forgetting the
+.'I have 12 apples'.match(/\d/g)splits 12 into'1'and'2'. - A dot without a backslash.
/3.14/also matches3x14, because.means any character. Write/3\.14/. - Using the result of
matchright away. When nothing matches, the result isnull, andnull.lengthcauses an error. Add|| []. - Regex for something simple. Do you only want to know whether a text contains
@?text.includes('@')is easier to read.
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.