【问题标题】:Calling methods on the replacement argument when using .replace() [duplicate]使用 .replace() 时在替换参数上调用方法 [重复]
【发布时间】:2019-12-17 22:07:14
【问题描述】:

我最近在玩.replace(),发现以下行为很奇怪。取下面两个代码sn-ps:

const str = "Hello world";
const res = str.replace(/(o)/g, "$1".repeat(3));
console.log(res); // Hellooo wooorld (which I expected)

上面打印了"Hellooo wooorld",这是我的预期,因为我在匹配的o字符上使用.repeat(3)

但是,当我应用相同的逻辑并使用.toUpperCase() 时,我的字符串保持不变:

const str = "Hello world";
const res = str.replace(/(o)/g, "$1".toUpperCase());
console.log(res); // Hello world (expected HellO wOrld)

令我惊讶的是,上面没有工作,因为它打印了原始字符串而不是"HellO wOrld"那么,为什么第一个代码 sn-p 有效,而第二个无效?。我知道我可以为此使用replacement 函数,但我更关心的是为什么第一个 sn-p 有效,而第二个无效。

【问题讨论】:

  • "$1".toUpperCase() 仍然是 "$1""$1".repeat(3)"$1$1$1"。您将这些字符串传递给函数,而不是方法调用。

标签: javascript replace


【解决方案1】:

计算第二个参数的表达式将替换传递参数中所有出现的$#-like 字符串。在第一个代码中,传递的参数是'$1$1$1'

const res = str.replace(/(o)/g, "$1".repeat(3));
// interpreter first parses the expression in the second parameter,
// so it knows what to pass to replace:
const res = str.replace(/(o)/g, "$1$1$1");
// THEN the function call occurs

在第二个代码中,在'$1' 上调用toUpperCase 会产生相同的字符串$1

const res = str.replace(/(o)/g, "$1".toUpperCase());
// interpreter first parses the expression in the second parameter,
// so it knows what to pass to replace:
const res = str.replace(/(o)/g, "$1");
// THEN the function call occurs

【讨论】:

  • 啊,完全有道理,我应该看到的。谢谢
猜你喜欢
  • 1970-01-01
  • 2015-10-11
  • 2011-02-19
  • 2015-10-30
  • 2019-01-08
  • 1970-01-01
  • 1970-01-01
  • 2021-11-17
  • 1970-01-01
相关资源
最近更新 更多