JavaScript RegEx Cheatsheet

Sararellano
5 min readJun 3, 2022
JS regex cheatsheet

Hello!

I’ve found information about RegEx in JavaScript and I thought it would be interesting to share it with everyone and also, for me to save it and have it always available like a cheatsheet.
Also, to test everything I recommended you the page https://regex101.com/

So… let’s start!

What is RegEx?

RegEx (regular expressions) are a series of symbols that will allow us to define search patterns in text strings.

Regex in JavaScript

In JavaScript, a RegEx is an object that describes a sequence of characters used for defining a search pattern, for example /^a…s$/ this regEx select any 5 letter string starting with “a” and ending with “s”:

  • abs -> no match
  • alias -> match
  • Alias -> no match

There are two ways to create a RegEx :

1. Using a regular expression literal: consists of a pattern enclosed between “/”:

const regularExp = /abc/;

2. Using the RegExp() constructor function:

const regularExp = new RegExp('abc');

Metacharacters

There’re characters that are interpreted in a special way by a RegEx engine: [].^$*+?{}()\|

  • []

Specify a set of characters you want to match:

[abc] -> 'Hello world' -> No matches
[abc] -> 'Say goodbye' -> 3 matches
[a-e] -> is same as [abcde]
[1-4] -> is same as [1234]
[^abc] -> means any character except a, b or c
[^0-9] -> means any non-digit character
  • .

A period “.” matches any single character (except newline ‘\n’)

.. -> means 2 characters -> 'Ey' -> 1 Match
.. -> 'abcd' -> 2 matches
  • ^

To check if a string starts with a specific character:

^a -> 'abc' -> match
^ac -> 'abc' -> No match
^ab -> 'abc' -> match
  • $

To check if a string ends with a specific character:

a$ -> 'Sara' -> match
ab$ -> 'Hello' -> no match
lo$ -> 'Hello' -> match
  • +

Matches one or more occurrences of the pattern left to it:

he+l -> 'hello' -> match
he+o -> 'hello' -> no match ('he' has to be before 'o')
ma+n -> 'man' -> matches
ma+n -> 'mmaan' -> matches (it recognizes duplicate letters)
  • ?

Matches zero or one occurrence of the pattern left to it:

he?l -> 'hello' -> match
he?o -> 'hello' -> no match
ma?n -> 'man' -> match
ma?n -> 'mmaan' -> no matches (it doesn't recognize duplicate letters)
  • *

Matches zero or more occurrences:

ma*n -> 'woman' -> match
ma*n -> 'main' -> No match ('n' has to be before 'ma')
ma*n -> 'maaan' -> match (it recognizes duplicate letters)

+ and * are very similar, but there is a little difference: * means zero-or-more, and + means one-or-more. So the difference is that the empty string would match the second expression but not the first (because the expression is optional).

  • {}

{n, m} this means at least n and at most m repetitions of the pattern left to it:

a{2,3} -> 'abc saara' -> 1 match (saara)
a{2,3} -> 'aabc saara' -> 2 matches
[0-9]{2,4} -> 'ab123cxde' -> 1 match (123)
[0-9]{2,4} -> '12 and 345678' -> 3 matches (12, 3456, 78)
  • ()

It’s used to group sub-patterns. For instance, (a|b|c)xz match any string that matches either a or b or c followed by xz

(a|b|c)xz -> 'abxz' -> 1 match (bxz)
(a|b|c)xz -> 'axz cabxz' -> 1 matches
  • |

Is used for alternation (or):

a|b -> 'abc' -> 2 matches
a|b -> 'hello' -> no matches

Special Sequences

Special sequences make commonly used patterns easier to write:

  • \A

Matches if the specified characters are at the start of a string:

\Athe -> ‘the sun’ -> match 
\Athe -> ‘in the sun’ - not match
  • \Z

Matches if the specified characters are at the end of a string:

JavaScript\Z -> ‘I like JavaScript’ -> match
JavaScript\Z -> ‘JavaScript is a frontend language’ -> no match
  • \b

Matches if the specified characters are at the beginning or end of a word:

\bfoo -> ‘a football team’ -> match
foo\b -> ‘a football team’ -> no match
foo\b -> ‘the afootest’ -> no match
  • \B

Matches if the specified characters aren’t at the beginning or end of a word. It’s the opposite of \b

\Bfoo -> ‘a football team’ -> no match
foo\B -> ‘a football team’ -> match
foo\B -> ‘the afootest’ -> match
  • \d

Matches any decimal digit. Equivalent to [0–9]

\d -> ‘12abc3’ -> 3 matches (1, 2, 3)
\d -> ‘JavaScript’ -> no match
  • \D

Matches any non-decimal digit. Equivalent to [⁰-9]

\D -> 1ab34”7 -> 3 matches (a, b, “)
\D -> 1345 -> no match
  • \s

Matches where a string contains any whitespace character. Equivalent to [\t\n\r\f\v]

\s ->’RegEx’ -> no match
\s -> ‘Regular expression’ -> 1 match
  • \S

Matches where a string contains any non-whitespace character. Equivalent to [^\t\n\r\f\v]

\S -> ‘a bc’ -> 3 matches (a, b, c)
\S -> ‘ ‘ -> no matches
  • \w

Matches any alphanumeric character. Equivalent to [a-zA-Z0–9_]

\w -> 12&”:;c -> 3 matches (1, 2, c)
\w -> $%& -> no matches
  • \W

Matches any non-alphanumeric character. Equivalent to [^a-zA-Z0–9_]

\W -> 12&”:;c -> 4 matches (&, “, :, ;)
\W -> JavaScript -> no matches

How to use RegEx

String Methods

  • exec() -> Executes a search for a match in a string and returns an array of information. It returns null on a mismatch.
  • test() -> Tests for a match in a string and returns true or false.
  • match() -> Returns an array containing all the matches. It returns null on a mismatch.
  • matchAll() -> Returns an iterator containing all of the matches.
  • search() -> Test for a match in a string and returns the index of the match. It returns -1 if the search fails.
  • replace() -> Searches for a match in a string and replaces the matched substring with a replacement substring.
  • split() -> Break a string into an array of substrings.

Regex Flag

g: performs a global match (find all matches).

m: performs multiple match.

i: performs case-insensitive matching.

const string = 'Hello hello hello';// performing a replacement
const result1 = string.replace(/hello/, 'world');
console.log(result1); // Hello world hello
// performing global replacement
const result2 = string.replace(/hello/g, 'world');
console.log(result2); // Hello world world
// performing case-insensitive replacement
const result3 = string.replace(/hello/i, 'world');
console.log(result3); // world hello hello
// performing global case-insensitive replacement
const result4 = string.replace(/hello/gi, 'world');
console.log(result4); // world world world

Examples

// Splitting strings into array elements
const regex = /[\s,]+/,
result = 'hello world! '.split(regex);
console.log(result); // ['Hello', 'world!', '']
// Searching the phone number pattern
const regex = /(\d{3})\D(\d{3})-(\d{4})/g,
result = regex.exec('My phone number is: 666 123-4567.');
console.log(result); // ['666 123-4567', '666', '123', '4567']

Validating a phone number

function validatePhone(num) {
const regex = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/g;

// Check if the phone number is valid
let result = num.match(regex);
if (result) {
console.log(The number is valid.);
} else {
let num = prompt('Enter number in XXX-XXX-XXXX format:');
validatePhone(num);
}
}
let number = prompt('Enter a number XXX-XXX-XXXX');
validatePhone(number);

Validating the email adress

function validateEmail(email) {
const regex = /\S+@\S+\.\S+/g;
// check if the email is valid
let result = regex.test(email);
if (result) {
console.log('The email is valid');
} else {
let newEmail = prompt('Enter a valid email:');
validateEmail(newEmail);
}
}
let email = prompt('Enter an email:');
validateEmail(email);

I hope you find it useful!

--

--