Javascript如何在replace()函数中跳过$&

时间:2019-05-15 11:16:04

标签: javascript regex replace reference

如何跳过在replace()函数中替换特殊的$&

我尝试添加\($ \&),但没有任何结果

var url = 'http://www.example.com/?a=b&c=c&d=$cid$&e=e';
var txt = 'Lorem ipsum dolor sit amet, {link} consectetur adipiscing elit. {link} id porttitor quam rhoncus in.';
var output = txt.replace(/{link}/gi, url);
console.log(output);
.as-console-wrapper { max-height: 100% !important; top: auto; }

1 个答案:

答案 0 :(得分:0)

使用$$代替$

或使用此url.replace(/\$/g, '$$$$')

修复网址本身

var url = 'http://www.example.com/?a=b&c=c&d=$cid$&e=e';
var txt = 'Lorem ipsum dolor sit amet, {link} consectetur adipiscing elit. {link} id porttitor quam rhoncus in.';
var output = txt.replace(/{link}/gi, url.replace(/\$/g, '$$$$'));
console.log(output);