Согласно стандарту ECMA-262 , String.prototype.replace вызывает RegExp.prototype [@@ replace] , что говорит:
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')
это фактически:
- result (undefined), results =
[]
, lastIndex = 0
- результат =
'asdf'
, результаты = [ 'asdf' ]
, lastIndex = 4
- результат =
''
, результаты = [ 'asdf', '' ]
, lastIndex = 4
, AdvanceStringIndex
, установите lastIndex равным 5
- result =
null
, results = [ 'asdf', '' ]
, return
Поэтому существует 2 совпадения.