5

Possible Duplicate:
How can I match multiple occurrences with a regex in JavaScript similar to PHP's preg_match_all()?

In Javascript, is it possible to find the starting and ending indices of all substrings within a string that match a regular expression?

Function signature:

function getMatches(theString, theRegex){
    //return the starting and ending indices of match of theRegex inside theString
    //a 2D array should be returned
}

For example:

getMatches("cats and rats", /(c|r)ats/);

should return the array [[0, 3], [9, 12]], which represents the starting and ending indices of "cats" and "rats" within the string.

Community
  • 1
  • 1
Anderson Green
  • 27,734
  • 61
  • 179
  • 311

2 Answers2

12

Use match to find all substrings that match the regex.

> "cats and rats".match(/(c|r)ats/g)
> ["cats", "rats"]

Now you can use indexOf and length to find the start/end indices.

sachleen
  • 29,893
  • 8
  • 74
  • 71
2
function getMatches(theString, theRegex){
    return theString.match(theRegex).map(function(el) {
        var index = theString.indexOf(el);
        return [index, index + el.length - 1];
    });
}
getMatches("cats and rats", /(c|r)ats/g); // need to use `g`
xdazz
  • 154,648
  • 35
  • 237
  • 264