我偶然发现了一个(对我来说)令人惊讶的事实。
console.log("asdf".replace(/.*/g, "x"));
为什么要换两个?似乎任何没有换行符的非空字符串都会为此模式产生两个替换。使用替换函数,我可以看到第一个替换是针对整个字符串,第二个是针对空字符串。
最佳答案
根据 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:
b. Let nextIndex be AdvanceStringIndex(S, thisIndex, fullUnicode).
因此在
'asdf'.replace(/.*/g, 'x')
实际上是:[]
, 最后索引 = 0
'asdf'
, 结果 = [ 'asdf' ]
, 最后索引 = 4
''
, 结果 = [ 'asdf', '' ]
, 最后索引 = 4
, AdvanceStringIndex
, 将 lastIndex 设置为 5
null
, 结果 = [ 'asdf', '' ]
, 返回 因此有 2 场比赛。
关于javascript - 为什么 "asdf".replace(/.*/g, "x") == "xx"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61263151/