Theo tiêu chuẩn ECMA-262 , String.prototype.replace gọi RegExp.prototype [@@ thay thế] , cho biết:
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).
nơi rx
là /.*/g
vàS
là 'asdf'
.
Xem 11.c.iii.2.b:
b. Đặt next Index là AdvanceString Index (S, this Index, fullUnicode).
Do đó trong 'asdf'.replace(/.*/g, 'x')
đó thực sự là:
- kết quả (không xác định), kết quả =
[]
, last Index =0
- kết quả =
'asdf'
, kết quả =[ 'asdf' ]
, last Index =4
- result =
''
, results = [ 'asdf', '' ]
, last Index = 4
,AdvanceStringIndex
, thiết lastIndex để5
- kết quả =
null
, kết quả =[ 'asdf', '' ]
, trả lại
Do đó có 2 trận đấu.
"asdf".match(/.*/g)
return ["asdf", ""]