JavaScript RegExp sets index manually

What if you want to combine a string with a known position? Then you should cut this line from this position, and only after that you can perform the mapping. But what if a line is very large and you don’t want to cut it many times because it will create many new lines, this is bad for memory, for runtime. I wonder why there is an argument index in String.indexOfand there are no such opportunities for String.searchand all methods of RegExp?

var rgx1 = /some pattern/g
var rgx2 = /other pattern/
var match = rgx1.exec(VeryBigString)
if (match !== null) {
  rgx2.lastIndex = match.index
  var result = rgx2.exec(VeryBigString)
}

Here I tried to set the property lastIndex, but failed. Regexp has this property, but does not want to accept changes to it.

+4
source share
1 answer

RegExp#lastIndex .

var regExp = /a/g,
    result,
    string = 'aaaaaaaa';

regExp.lastIndex = 4;

while ((result = regExp.exec(string)) !== null) {
    console.log(`Found ${result[0]}. Next starts at ${regExp.lastIndex}.`);
}
Hide result
+3

Source: https://habr.com/ru/post/1692817/


All Articles