13

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));
  }

2 Answers 2

12

.match returns a new array with the following properties:

The index property is set to the position of the matched substring within the complete 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.com/2004/11/07/#a-15.10.6.2

match.index will provide what you need.

Sign up to request clarification or add additional context in comments.

1 Comment

interesting....I had noticed that Chrome puts the index in the array (assuming you don't have a /g ....whereby there would be multiple matches and it wouldn't make sense to have a single index). If this is supported by all reasonable browsers (...?), that's perfect.
1

Alternatively:

if (match && match[0]) {
    console.log ("end of match is at index " + (str.indexOf(match[0]) + match[0].length));
}

1 Comment

I guess you are right, that if you do an indexOf on match[0] it will always be the first occurance. Unless there is a weird regular expression that might, say, give you the second occurance of a string...?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.