javascript - 使用 .replace() 时调用替换参数上的方法

标签 javascript replace

我正在玩.replace()最近发现以下行为很奇怪。获取以下两个代码片段:

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

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

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

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

令我惊讶的是,上面的内容不起作用,因为它打印了原始字符串,而不是 "HellO wOrld"那么,为什么第一个代码片段可以工作,但第二个代码片段却不行?。我知道我可以使用replacement函数,但我更关心理解为什么第一个片段有效,而第二个片段无效。

最佳答案

第二个参数求值的表达式将替换传递参数中所有出现的类似 $# 的字符串。在第一个代码中,传递的参数是'$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

关于javascript - 使用 .replace() 时调用替换参数上的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57442358/

相关文章:

excel - 将字符串中的一个字符替换为另一个字符

javascript - 如何使用 HTML 和 JS 在本地保存图像?

javascript - 匹配字符串的起始字符

JavaScript - 替换和创建变量

r - 当存在应保留 NA 的 NA 时,在数据框中填充数据

python - pandas str.replace - 如果正则表达式在将字符串转换为数字时未能避免 NaN,则保留当前值

javascript - 替换 JavaScript 中的表情符号列表

javascript - 在 Canvas 上绘制平滑的线条

javascript - 倾斜文本时重复 hAxis 标签 - Google 图表

IE11 中排序函数的 Javascript 语法错误