Javascript - String Pattern-Matching Methods

Introduction

The String type has several methods to do pattern-match.

match() method is essentially the same as calling a RegExp object's exec() method.

The match() method accepts a single argument, which is either a regular-expression string or a RegExp object.

var text = "cat, bat, sat, fat";
var pattern = /.at/;

//same as pattern.exec(text)
var matches = text.match(pattern);
console.log(matches.index);        //0
console.log(matches[0]);           //"cat"
console.log(pattern.lastIndex);   //0

The array returned from match() is the same array returned from RegExp's exec() method:

  • the first item is the string that matches the entire pattern, and
  • each other item (if applicable) represents capturing groups in the expression.

search() accepts a regular expression specified by either a string or a RegExp object.

search() method returns the index of the first pattern occurrence in the string or -1 if it's not found.

search() begins looking for the pattern at the beginning of the string.

var text = "cat, bat, sat, fat";
var pos = text.search(/at/);
console.log(pos);   //1

Here, search(/at/) returns 1, which is the first position of "at" in the string.