Order of calling string replacement functions

When calling String.replace with the replace function, we can get the offsets of the subscripts.

var a = [];
"hello world".replace(/l/g, function (m, i) { a.push(i); });
// a = [2, 3, 9]

      

In the above example, we get a list of offsets for the matched characters l

.

Can I count on implementations to always refer to the match function in ascending order? That is: can I be sure that the result above will always be [2,3,9]

, and not [3,9,2]

or any other permutation of these offsets?

I've looked through the spec and I can't find anything that indicates the order of the call, but perhaps it has something to do with how the regex engine is supposed to be implemented?

+2


source to share


2 answers


Can I count on implementations to always refer to the match function in ascending order?



Absolutely yes. Matches are processed from left to right in the original string, because left to right is how regex engines work in a string.

+3


source


I guess you shouldn't worry about that. You can also use a pattern Fookahead

that starts at the beginning of a line:



"hello world".replace(/(?=l)/g, function (m, i) { a.push(i); });

      

0


source







All Articles