JS: RegExp 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.

Basic Example

Check if a string contains repeated t

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

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

Example: Regexp Replace

const xx = `i have 1 cat, and my mom has 2 cats.`;

const yy = xx.replaceAll(
  /(\d+) cat/g,
  `$1 dog`,
);

console.log(yy === `i have 1 dog, and my mom has 2 dogs.`);

Example: Capture Numbers

const xtext = "there are 394 cats and 98 dogs.";
const regex = /\d+/gi;
console.log(xtext.match(regex));
// [ "394", "98" ]

Example: Capture HTML Tag Attributes

// capture the attribute values in a HTML image tag
const xtext = `<img class="i" src="cat.jpg" alt="my cat">`;
const result = xtext.match(/<img class="([^"]+)" src="([^"]+)" alt="([^"]+)">/);
console.log(result);
/*
[
  '<img class="i" src="cat.jpg" alt="my cat">',
  "i",
  "cat.jpg",
  "my cat",
  index: 0,
  input: '<img class="i" src="cat.jpg" alt="my cat">',
  groups: undefined
]
*/

JavaScript. Regular Expression