Introduction

Regular expressions is a powerful way of string search and replace. In JavaScript, it is integrated in String methods search, match and replace.

A regular expression or, shortly, a regexp consists of a pattern and optional flags.

A basic regexp search is same as a substring search. The regexp object is created as a string surrounded by slashes "/":

*!*
regexp = /att/
*/!*

str = "Show me the pattern!"

alert( str.search(regexp) ) // 13

In the example above, method str.search returns the position of a regexp att in the string Show me the pattern!.

Colors

There’s a color scheme:

  • the pattern - red
  • the subject string - blue
  • the result - green

In real life, regexps may be more complicated. The regexp below searches emails:

*!*
regexp = /[a-z0-9!$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!$%&'*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[A-Z]{2}|com|org|net|edu|gov|mil|biz|info|mobi|name|aero|asia|jobs|museum)\b/
*/!*

str = "Let's find an email@gmail.com here"

alert( str.match(regexp) )   // email@gmail.com

Method str.match gives the result of match.

After the tutorial you will fully understand the regexp above, and more be able to build more complicated ones.

In JavaScript console, you can test regexps by a direct call to str.match:

alert( "lala".match(/la/) )

Here, to keep the demos a little bit shorter, we’ll use a convenience showMatch function which outputs the match:

showMatch( "Show me the pattern!", /att/ )  // "att"

function showMatch(str, reg) {
  var res = [], matches
  while(true) {
    matches = reg.exec(str)
    if (matches === null) break
    res.push(matches[0])
    if (!reg.global) break
  }
  alert(res)
}

In next steps we start learning the syntax of regular expressions.

Tutorial

Donate

Donate to this project