Is there any Javascript function which does regex match from specified index
Is there function which work as:
var regex=/\s*(\w+)/; var s="abc def "; var m1=regex.exec(s,0); // -> matches "abc" var m2=regex.exec(s,3); // -> matches "def"
I know the alternative is:
var regex=/\s*(\w+)/; var s="abc def "; var m1=regex.exec(s); // -> matches "abc" var m2=regex.exec(s.substring(3)); // -> matches " def"
But I worry about that if s is very long and s.substring is called many times, some implementation may work in bad efficiency in which copy long strings many times.
Answers
Yes, you can make exec start at a particular index if the regex has the g global modifier.
var regex=/\s*(\w+)/g; // give it the "g" modifier regex.lastIndex = 3; // set the .lastIndex property to the starting index var s="abc def "; var m2=regex.exec(s); // -> matches "def"
If your first code example had the g modifier, then it would work as you wrote it, for the very same reason above. With g, it automatically sets the .lastIndex to the index past the end of the last match, so the next call would start there.
So it depends on what you need.
If you don't know how many matches there will be, the common approach would be to run exec in a loop.
var match, regex = /\s*(\w+)/g, s = "abc def "; while(match = regex.exec(s)) { alert(match); }
Or as a do-while.
var match, regex = /\s*(\w+)/g, s = "abc def "; do { match = regex.exec(s); if (match) alert(match); } while(match);