De acordo com o padrão ECMA-262 , String.prototype.replace chama RegExp.prototype [@@ replace] , que diz:
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).
onde rxestá /.*/ge Sestá 'asdf'.
Ver 11.c.iii.2.b:
b. Seja nextIndex AdvanceStringIndex (S, thisIndex, fullUnicode).
Portanto, na 'asdf'.replace(/.*/g, 'x')verdade é:
- resultado (indefinido), resultados =
[], lastIndex =0
- resultado =
'asdf', resultados = [ 'asdf' ], lastIndex =4
- resultado =
'', = resultados [ 'asdf', '' ], lastIndex = 4, AdvanceStringIndex, ajustado para lastIndex5
- resultado =
null, resultados = [ 'asdf', '' ], retorno
Portanto, existem 2 correspondências.
"asdf".match(/.*/g)return ["asdf", ""]