JS: RegExp Tutorial

By Xah Lee. Date: . Last updated: .

RegExp stands for “regular expression”. It lets you check if a string has certain pattern, or replace parts of string by pattern.

Basic Example

// check if a string contains repeated t

const ss = "something in tthe water";

const result = ss.search( /tt+/ );

console.log (result); // 13
// return value is the start position of match
// if not found, returns -1

/tt+/ means, 1 t, followed by 1 or more t.

The syntax /…/ is a literal expression for regex. It return a RegExp object. [see JS: RegExp Object]

In between the slashes, is the regexp syntax for a pattern.

[see JS: RegExp Syntax]

The string.search( … ) means search the pattern in string string.

search is a string method. It returns the first character's index where the pattern matches. If the pattern is not found, it returns -1.

[see JS: String.prototype.search]

Example of Checking Email Pattern

Let's say you have a string, and you want to know if it has the email address form like “xyz@example.com”.

// check if a string contains a simple email pattern

const ss = "something xyz@example.com";

console.log( ss.search( /[a-z]+@[a-z]+\..../ ) ); // 10
// return value is the start position of match
// if not found, returns -1

Note: if you never worked with regexp before, don't worry. Regexp is not something you understand fully the first day. It takes many months of use to be comfortable.

Regex Example with If

It's common to use regex with if.

If a pattern is found, do something, else, do something else.

const text = "my cat";

// search for cat or cot or cut
const result = text.search(/c[aou]t/);

if ( result !== -1) {
} else {

// prints yay

Regexp Replace Example

Regexp can also be used to replace parts of a string that matches a pattern.

// example of regex replace
// add a alt attribute to a HTML image tag.

const x1 = '<img src="cat.jpg">';

const x2 = x1.replace(/<img src="([-_\w]+)\.jpg">/, '<img src="$1.jpg" alt="$1">');

console.log(x2); // <img src="cat.jpg" alt="cat">

[see JS: String.prototype.replace]

Regexp Example, Get All Captured Patterns

// example of regex “match” method
// capture the attribute values in a image tag

const str = '<img class="i" src="cat.jpg" alt="my cat">';

const result = str.match(/<img class="([^"]+)" src="([^"]+)" alt="([^"]+)">/);

console.log(result[0]); // <img class="pict" src="cat.jpg" alt="my cat">
console.log(result[1]); // i
console.log(result[2]); // cat.jpg
console.log(result[3]); // my cat

[see JS: String.prototype.match]

To learn more, see:

JS RegExp

  1. RegExp Tutorial
  2. RegExp Syntax
  3. Regex Find/Replace

JavaScript Basics

  1. JavaScript Basics
  2. true, false
  3. Operators
  4. Branch Control
  5. Loop
  6. Array Basics
  7. Object Basics
  8. RegExp Basics
Like it? Help me by telling your friends. Or, Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials