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
2010-02-19 10:49:16
Thanks for your help! Can you tell me also how do I find the indexes of multiple matches?
stagas
2010-02-19 11:10:46
@stagas: In that case you should better use `exec`.
Gumbo
2010-02-19 11:13:34
+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
2010-02-19 10:51:37
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
2010-02-19 11:38:26