gpt4 book ai didi

javascript - javascript string.replace 是线性的吗?

转载 作者:行者123 更新时间:2023-11-30 10:03:34 24 4
gpt4 key购买 nike

是 javascript 的 string.replace 线性替换还是有一些时髦的优化?基本上,我的问题是这段代码的结果是按数字顺序排列的吗?

  var index = 0;
html = html.replace(/replaceIndex/g, function (match, capture) {
return index++;
});

我觉得这个问题的答案是“它取决于 x”,其中 x 是 firefox、chrome、v8、rhino 等。

最佳答案

ES5似乎没有指定调用顺序:

for each matched substring, call the function with the following m + 3 arguments.

但是,ES6 可以。 String.prototype.replace使用 RegExp.prototype[@@replace]哪个(恢复)表现得像

21.2.5.8 RegExp.prototype [ @@replace ] ( string, replaceValue )

  • Let S be ToString(string).
  • Let results be a new empty List.
  • Repeat
    • Let result be RegExpExec(rx, S).
    • Append result to the end of results.
  • Let accumulatedResult be the empty String value.
  • Let nextSourcePosition be 0.
  • Repeat, for each result in results,
    • Let position be ToInteger(Get(result, "index")).
    • Let position be max(min(position, lengthS), 0).
    • Let replValue be Call(replaceValue, undefined, replacerArgs).
    • Let replacement be ToString(replValue).
    • If position ≥ nextSourcePosition, then
      • NOTE position should not normally move backwards. If it does, it is an indication of an ill-behaving RegExp subclass or use of an access triggered side-effect to change the global flag or other characteristics of rx. In such cases, the corresponding substitution is ignored.
      • Let accumulatedResult be the String formed by concatenating the code units of the current value of accumulatedResult with the substring of S consisting of the code units from nextSourcePosition (inclusive) up to position (exclusive) and with the code units of replacement.
      • Let nextSourcePosition be position + matchLength.
  • If nextSourcePositionlengthS, return accumulatedResult.
  • Return the String formed by concatenating the code units of accumulatedResult with the substring of S consisting of the code units from nextSourcePosition (inclusive) up through the final code unit of S (inclusive).

关于javascript - javascript string.replace 是线性的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30447529/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com