谁知道为什么
"why?? <abc> and <a b c> and <a b>".replace( /<([^>]+)>/g, "\$$1" );
返回
"why?? $1 and $1 and $1"
代替
"why?? $abc and $a b c and $a b"
没有转义的$,结果符合预期
"why?? <abc> and <a b c> and <a b>".replace( /<([^>]+)>/g, "$1" )
//"why?? abc and a b c and a b"
我尝试了各种技巧,例如
"why?? <abc> and <a b c> and <a b>".replace( /<([^>]+)>/g, String.fromCharCode( 36 ) + "$1" );
最后,我设法使用一个函数作为替换字符串(见下文)获得了我想要的输出,但我想知道我做错了什么。提前致谢。
"why?? <abc> and <a b c> and <a b>".replace( /<([^>]+)>/g, function(m,m1,m2,p){return '$' + m1; } )
请您参考如下方法:
在 JavaScript 中,反斜杠只是从无法识别的转义序列中删除。 \$
不是字符串文字中可识别的转义序列,因此:
"\$$1"
意思和这个一样:
"$$1"
并且在 replace
替换字符串中,$$
表示“文字美元符号”。
你要的是这个:
"$$$1"
其中 $$
变为 $
而 $1
变为例如abc
。
(换句话说:在 replace
替换字符串中“转义”美元符号的方法是将其加倍,不是在其前面加上反斜杠。 )