3

I have tried the following:

var stringToBeReplaced = "$";
var result = stringToBeReplaced.replace("$", "$$$$");

It works in modern browsers and I get "$$" in result. But to my surprise, when I run it over IE8 or older, I get "$$$$" in result. Is it a browser bug? Is there a cross browser solution avoiding browser detection? Just vainilla js please, no frameworks.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
gztomas
  • 3,030
  • 3
  • 27
  • 38

2 Answers2

3

This probably works :

var result = stringToBeReplaced.replace(/(\$)/g, "$1$1");

but I must confess I have no IE to test.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
2

You can try replace with callback:

'$'.replace('$', function($0) { return '$$'; });
"$$"

PS: I have tested it on Firefox, Chrome and IE8

anubhava
  • 761,203
  • 64
  • 569
  • 643