If I use string.match() with a regex, I'll get back the matched string, but not the index into the original string where the match occurs. If I do string.search(), I get the index, but I don't necessarily know how long the matched part of the string is. Is there a way to do both, so I can get the index of the end of the match in the original string?
I suppose I could do one after the other (below), assuming they return the same results but in a different way, but that seems ugly and inefficient, and I suspect there is a better way.
var str = "Fear leads to anger. Anger leads to hate. Hate leads to suffering";
var rgx = /l[aeiou]+d/i;
var match = str.match(rgx);
if (match && match[0]) {
var i = str.search(rgx);
console.log ("end of match is at index " + (i+match[0].length));
}
If I use string.match() with a regex, I'll get back the matched string, but not the index into the original string where the match occurs. If I do string.search(), I get the index, but I don't necessarily know how long the matched part of the string is. Is there a way to do both, so I can get the index of the end of the match in the original string?
I suppose I could do one after the other (below), assuming they return the same results but in a different way, but that seems ugly and inefficient, and I suspect there is a better way.
var str = "Fear leads to anger. Anger leads to hate. Hate leads to suffering";
var rgx = /l[aeiou]+d/i;
var match = str.match(rgx);
if (match && match[0]) {
var i = str.search(rgx);
console.log ("end of match is at index " + (i+match[0].length));
}
Share
Improve this question
asked Mar 26, 2011 at 6:25
robrob
10.1k7 gold badges44 silver badges73 bronze badges
2 Answers
Reset to default 12.match
returns a new array with the following properties:
The index property is set to the position of the matched substring within the plete string S.
The input property is set to S.
The length property is set to n +1.
The 0 property is set to the matched substring (i. e. the portion of S between offset i inclusive and offset e exclusive).
For each integer i such that i >0 and i <= n, set the property named ToString(i) to the ith element of r's captures array.
From http://bclary./2004/11/07/#a-15.10.6.2
match.index
will provide what you need.
Alternatively:
if (match && match[0]) {
console.log ("end of match is at index " + (str.indexOf(match[0]) + match[0].length));
}