user918671
user918671

Reputation: 49

How to get both the start and end positions of regex matches in JavaScript?

I just wish to find the start and end positions of the substrings I am searching for. Any Ideas as to how this can be done?

Upvotes: 4

Views: 6060

Answers (2)

gislikonrad
gislikonrad

Reputation: 3581

Here's a jsfiddle that shows how it's done...

https://jsfiddle.net/cz8vqgba/

var regex = /text/g;
var text = 'this is some text and then there is some more text';
var match;
while(match = regex.exec(text)){
    console.log('start index= ' +(regex.lastIndex - match[0].length));   
    console.log('end index= ' + (regex.lastIndex-1));
}

This will get you the start and end index of all matches in the string...

Upvotes: 10

Gras Double
Gras Double

Reputation: 16373

no need at all to traverse the haystack two times (which would likely be less efficient)

you can do either:

"foobarfoobar".match(/bar/);

or:

/bar/.exec("foobarfoobar");

both return this object :

{
    0: 'bar'
    index: 3
    input: 'foobarfoobar'
}

so if you want start and end positions, you just have to do something like:

var needle = /bar/;
var haystack = 'foobarfoobar';

var result = needle.exec(haystack);
var start = result.index;
var end = start + result[0].length - 1;

Note this simple example gives you only the first match; if you expect several matches, things get a little bit more complicated.

Also, I answered for regex as it is in the title of the question, but if all you need is string match you can do nearly the same with indexOf().

Upvotes: 7

Related Questions