Javascript 使用.replace()时对替换参数调用方法

Javascript 使用.replace()时对替换参数调用方法,javascript,replace,Javascript,Replace,我最近在玩.replace(),发现以下行为很奇怪。以以下两个代码段为例: const str=“你好世界”; 常量res=str.replace(/(o)/g,“$1”。重复(3)); console.log(res);//Hellooo woorld(我预期的)第二个参数求值的表达式将替换传递的参数中出现的所有类似于$\code>的字符串。在第一个代码中,传递的参数是'$1$1': const res = str.replace(/(o)/g, "$1".repeat(3)); // in

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

const str=“你好世界”;
常量res=str.replace(/(o)/g,“$1”。重复(3));

console.log(res);//Hellooo woorld(我预期的)
第二个参数求值的表达式将替换传递的参数中出现的所有类似于
$\code>的字符串。在第一个代码中,传递的参数是
'$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

“$1”。toUpperCase()
仍然是
“$1”
<代码>“$1”。重复(3)
“$1$1”
。你将这些字符串传递给函数,而不是方法调用。啊,完全有道理,我应该看到这一点。谢谢