JS: Regular Expression Tutorial

By Xah Lee. Date: . Last updated: .

What is Regular Expression

Regular Expression (or regex in short) is a character sequence that represent a pattern of text. For example, you can use it to find all numbers in a file.

Regex is used by many functions to check if a string contains certain pattern, or extract it, or replace it with other text.

Regex Pattern and Flags

Regular Expression has 2 parts:

Create Regex Object

Example. Find Index of Match

Check if a string contains repeated “t”.

console.log("something in tthe water".search(/tt+/));
// 13

/*
return the start position of match
if not found, returns -1
*/

Example. Regex Replace

console.log(`i have 1 cat, he has 2 cats.`.replaceAll(/(\d+) cat/g, `$1 dog`));
// i have 1 dog, he has 2 dogs.

Example. Capture Numbers

console.log("there are 394 cats and 98 dogs.".match(/\d+/g));
// [ "394", "98" ]

JavaScript. Regular Expression