Відповідно до стандарту ECMA-262 , String.prototype.replace викликає RegExp.prototype [@@ substitu] , який говорить:
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).
де rxє /.*/gі Sє 'asdf'.
Див. 11.c.iii.2.b:
б. Нехай nextIndex буде AdvanceStringIndex (S, thisIndex, fullUnicode).
Тому в 'asdf'.replace(/.*/g, 'x')ньому насправді:
- результат (невизначений), результати =
[], lastIndex =0
- result =
'asdf', results = [ 'asdf' ], lastIndex =4
- Результат =
'', = результати [ 'asdf', '' ], LastIndex = 4, AdvanceStringIndexвстановіть LastIndex до5
- результат =
null, результати = [ 'asdf', '' ], повернути
Тому є 2 матчі.
"asdf".match(/.*/g)return ["asdf", ""]