我正在玩.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/