How to use String match() to match string using regular expressions

Description

match() is the same as RegExp object's exec() method. The match() method accepts a regular-expression string or a RegExp object.

The first item of the returning array is the string that matches the entire pattern. Each other item of the returning array represents capturing groups in the expression.

Example


var text = "look, room, doom"; 
var pattern = /.oo/; 
        /*from w w  w  . j  ava  2  s.  c o  m*/
var matches = text.match(pattern); 
console.log(matches.index); //0 
console.log(matches[0]); //"oo" 
console.log(pattern.lastIndex); //0 

The code above generates the following result.





















Home »
  Javascript »
    Javascript Reference »




Array
Canvas Context
CSSStyleDeclaration
CSSStyleSheet
Date
Document
Event
Global
History
HTMLElement
Input Element
Location
Math
Number
String
Window