Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
46
rated 0 times [  49] [ 3]  / answers: 1 / hits: 6643  / 4 Years ago, fri, april 17, 2020, 12:00:00

I stumbled across a surprising (to me) fact.





console.log(asdf.replace(/.*/g, x));





Why two replacements? It seems any non-empty string without newlines will produce exactly two replacements for this pattern. Using a replacement function, I can see that the first replacement is for the entire string, and the second is for an empty string.


More From » regex

 Answers
2

As per the ECMA-262 standard, String.prototype.replace calls RegExp.prototype[@@replace], which says:



11. Repeat, while done is false
a. Let result be ? RegExpExec(rx, S).
b. If result is null, set done to true.
c. Else result is not null,
i. Append result to the end of results.
ii. If global is false, set done to true.
iii. Else,
1. Let matchStr be ? ToString(? Get(result, 0)).
2. If matchStr is the empty String, then
a. Let thisIndex be ? ToLength(? Get(rx, lastIndex)).
b. Let nextIndex be AdvanceStringIndex(S, thisIndex, fullUnicode).
c. Perform ? Set(rx, lastIndex, nextIndex, true).


where rx is /.*/g and S is 'asdf'.



See 11.c.iii.2.b:




b. Let nextIndex be AdvanceStringIndex(S, thisIndex, fullUnicode).




Therefore in 'asdf'.replace(/.*/g, 'x') it is actually:




  1. result (undefined), results = [], lastIndex = 0

  2. result = 'asdf', results = [ 'asdf' ], lastIndex = 4

  3. result = '', results = [ 'asdf', '' ], lastIndex = 4, AdvanceStringIndex, set lastIndex to 5

  4. result = null, results = [ 'asdf', '' ], return



Therefore there are 2 matches.


[#4125] Wednesday, April 15, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
josuea

Total Points: 609
Total Questions: 121
Total Answers: 104

Location: South Georgia
Member since Fri, Nov 13, 2020
4 Years ago
josuea questions
;