首页 > 解决方案 > 使用 .replace() 时在替换参数上调用方法

问题描述

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

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

上面的 print "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". 那么,为什么第一个代码片段有效,而第二个无效?. 我知道我可以为此使用替换功能,但我更关心理解为什么第一个片段有效,而第二个无效。

标签: javascriptreplace

解决方案


计算第二个参数的表达式将替换$#传递参数中所有出现的 -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

在第二个代码中,调用toUpperCase结果'$1'是相同的字符串,$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

推荐阅读