Javascript Regular Expressions match all instances of a pattern within a string.

Introduction

Use RegExp exec method and the global flag (g) in a loop to locate all instances of a pattern.

The following code searches any word that begins with t and ends with e, with any number of characters in between:

var searchString = "Now is the time and this is the time and that is the time"; 
var pattern = /t\w*e/g; 
var matchArray; // www  .j a v a  2s  .c o m

var str = ""; 

// check for pattern with regexp exec, if not null, process 
while((matchArray = pattern.exec(searchString))  != null) { 
       str+="at " + matchArray.index + " we found " + matchArray[0] + "\n"; 
} 
console.log(str); 



PreviousNext

Related