-1

I'm new in studying JavaScript. I have a String

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

and I want convert to

$1 plus $2 equal $3

So I using function Replace() Like this:

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

But I get this str:

$& plus $& equal $&

I change my code like this:

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

It doesn't work.I know my question maybe stupid.But I really don't know why the "\" cant escape "$". Forgive my poor English!

Damon Fu
  • 59
  • 1
  • 6
  • possible duplicate of [\`string.replace\` weird behavior when using dollar sign ($) as replacement](http://stackoverflow.com/questions/9423722/string-replace-weird-behavior-when-using-dollar-sign-as-replacement) –  Jun 02 '15 at 03:27
  • I'm puzzled how you could have learned that `$&` in the replacement string refers to the match, but not that you need `$$` (not `\$`) to specify a literal dollar sign. The two sequences are almost certainly described together in virtually any tutorial on `replace` replacement strings. –  Jun 02 '15 at 03:29

2 Answers2

1

According to the documentation here the replacement string for $ is $$, not \$. Given that, use this for your first replace line to produce the output you were looking for:

str2 = str2.replace(/(\d+)\s/g, '$$$&');
1337joe
  • 2,327
  • 1
  • 20
  • 25
0

Do this:

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

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

I prepare a Fiddle for you: https://jsfiddle.net/mez2yqb1/

alexandergs
  • 182
  • 2
  • 12