Javascript String match()

Introduction

The String match() method does pattern-match within the string.

str.match(regexp)
  • regexp - a regular expression object.

The match() is 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.

The following example demonstrates the use of the global and ignore case flags with match().

let str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
let regexp = /[A-E]/gi;
let matches_array = str.match(regexp);

console.log(matches_array);
let text = "cat, bat, sat, fat";     
let pattern = /.at/; 
                    /*from  ww  w .j  av  a 2 s  . c  o  m*/
// same as pattern.exec(text) 
let 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 when the RegExp object's exec() method.

The first item is the string that matches the entire pattern.

Each other item, if applicable, represents capturing groups in the expression.




PreviousNext

Related