javascript - 为什么 "asdf".replace(/.*/g, "x") == "xx"?

标签 javascript regex

我偶然发现了一个(对我来说)令人惊讶的事实。

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/.*/gS'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/

    相关文章:

    javascript - 如何键入嵌套对象的子属性?

    Python 正则表达式 - 从路径中提取目录

    python - 将单词与 Python 中的模式匹配

    javascript - addEventListener 到许多元素,用类选择它们

    javascript - 复选框上的 val() 返回一个元素而不是字符串文字

    javascript - jQuery 滚动到选定的行

    python - 正则表达式:当字符串包含正则表达式模式的一部分时匹配字符串的一部分

    Python:使用python从一行中提取以数字开头的匹配单词

    python - 将订单号与字母字符和数字的组合相匹配?

    javascript - 如何导入 SVG 文件以便访问其属性?