Javascript Regex函数replace()

时间:2015-06-02 01:59:02

标签: javascript regex

我是学习JavaScript的新手。我有一个字符串

var str2= "1 dollor plus 2 dollor equal 3 dollor";

我希望转换为

$1 plus $2 equal $3

所以我使用函数Replace()像这样:

str2 = str2.replace(/(\d+)\s/g, '\$$&");
str2 = str2.replace(/dollor/g, '');

但我得到了这个str:

$& plus $& equal $&

我改变了我的代码:

str2 = str2.replace(/(\d+)\s/g, '\$'+"$&");

它不起作用。我知道我的问题可能很愚蠢。但我真的不知道为什么“\”不能逃避“$”。 原谅我可怜的英语!

2 个答案:

答案 0 :(得分:1)

根据文档here$的替换字符串为$$,而不是\$。鉴于此,使用它作为您的第一个替换行来生成您正在寻找的输出:

str2 = str2.replace(/(\d+)\s/g, '$$$&');

答案 1 :(得分:0)

这样做:

var str2= "1 dollor plus 2 dollor equal 3 dollor";

str2 = str2.replace(/(\d+)\s/g, function replaceWithReposition(x){return "$" + x});

我为你准备一个小提琴: https://jsfiddle.net/mez2yqb1/