Javascript 使用正则表达式捕获的组作为字符串替换中的对象键
有人能帮助解释下面代码片段中显示的行为吗(从NodeJS 12控制台)?我试图用捕获组的结果替换字符串的一部分。这实际上是可行的,但当我将该捕获组结果用作对象中的键时,它实际上使用的是$1,而不是第一个捕获组Javascript 使用正则表达式捕获的组作为字符串替换中的对象键,javascript,node.js,Javascript,Node.js,有人能帮助解释下面代码片段中显示的行为吗(从NodeJS 12控制台)?我试图用捕获组的结果替换字符串的一部分。这实际上是可行的,但当我将该捕获组结果用作对象中的键时,它实际上使用的是$1,而不是第一个捕获组 > tmp { LOCALAS: 'world' } > a 'let the {{{LOCALAS}}} go around' > a.replace(/\{\{\{(.+)\}\}\}/g, "$1"); 'let the LOCALAS go aroun
> tmp
{ LOCALAS: 'world' }
> a
'let the {{{LOCALAS}}} go around'
> a.replace(/\{\{\{(.+)\}\}\}/g, "$1");
'let the LOCALAS go around'
> a.replace(/\{\{\{(.+)\}\}\}/g, tmp["LOCALAS"]);
'let the world go around'
> a.replace(/\{\{\{(.+)\}\}\}/g, tmp["$1"]);
'let the undefined go around'
> tmp["$1"] = "NO";
'NO'
> a.replace(/\{\{\{(.+)\}\}\}/g, tmp["$1"]);
'let the NO go around'
。。。一位朋友给了我一个有效的答案,但我仍然想知道为什么上面的行为会如此
> a.replace(/\{\{\{(.+)\}\}\}/g, function(_,k){return [tmp[k]]});
'let the world go around'
replace
不能/不会神奇地将字符串“$1”变为捕获组引用。参数tmp[“$1”]
将在您进行调用时进行计算(甚至在执行replace
的任何代码之前),因此从replace
的角度来看,它只是a.replace(/\{{{(.+)\}}}/g,未定义)
replace
不能/不会神奇地将字符串“$1”变为捕获组引用。参数tmp[“$1”]
将在您进行调用时进行计算(甚至在执行replace
的任何代码之前),因此从replace
的角度来看,它只是a.replace(/\{{{(.+)\}}}/g,未定义)代码>。