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

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 s1 = "something xyz@example.com";
const s2 = "from mary@abcdefg.org";
const s3 = "something xyz@example com";

console.log( s1.search( /[a-z]+@[a-z]+\..../ ) ); // 10
// return value is the start position of match

console.log( s2.search( /[a-z]+@[a-z]+\..../ ) ); // 5

console.log( s3.search( /[a-z]+@[a-z]+\..../ ) ); // -1
// if not found, returns -1

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 s1.search( … ) means search the pattern in string s1.

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

[see JS: Regex Find/Replace]

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

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">

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:

RegExp Topic

  1. JS: RegExp Tutorial
  2. JS: RegExp Syntax
  3. JS: Regex Find/Replace
  4. JS: RegExp Object
  5. JS: RegExp Constructor
  6. JS: RegExp.prototype

JavaScript Basics

  1. How to Run JavaScript
  2. JS: How to Use Browser Console
  3. JavaScript Basics
  4. JS: Data Types
  5. JS: true, false
  6. JS: Operators
  7. JS: Variable
  8. JS: Branch Control: if then else, switch
  9. JS: for while do Loop
  10. JS: Array Basics
  11. JS: Object Basics
  12. JS: RegExp Tutorial
  13. JS: Throw Try Catch Finally
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

Ask me question on patreon