views:

54

answers:

3

Is there a way to retrieve the (starting) character positions inside a string of the results of a regex match() in Javascript?

+3  A: 

match returns an object with a index property:

var match = "foobar".match(/bar/);
if (match) {
    alert("match found at " + match.index);
}

And for multiple matches:

var re = /bar/g,
    str = "foobarfoobar";
while ((match = re.exec(str)) != null) {
    alert("match found at " + match.index);
}
Gumbo
Thanks for your help! Can you tell me also how do I find the indexes of multiple matches?
stagas
@stagas: In that case you should better use `exec`.
Gumbo
+1  A: 

You can use the search method of the String object. This will only work for the first match, but will otherwise do what you describe. For example:

"How are you?".search(/are/);
// 4
Jimmy Cuadra
A: 

Here's what I came up with:

// Finds starting and ending positions of quoted text
// in double or single quotes with escape char support like \" \'

var patt=/'((?:\\.|[^'])*)'|"((?:\\.|[^"])*)"/igm;

while (match=patt.exec(str)) {
  console.log(match.index + ' ' + patt.lastIndex);
}
stagas
Thanks @Gumbo for your help
stagas