2

I've simplified the problem I ran into.
If I execute the following code in Chrome I get a strange behaviour:

var a = "$&";
var b = "aba";

var c = b.replace(/a/, a);

console.log(c); // expected output is: "$&b$&"
                // but output is:      "aba"

But if I execute the following code I get the expected output

var a = "c";
var b = "aba";

var c = b.replace(/a/, a);

console.log(c); // expected output is: "cbc"
                // and output is:      "cbc"

Any ideas how to solve this?
Is this a bug?
Do I have to escape the string in variable a in some ways?

JDB
  • 25,172
  • 5
  • 72
  • 123

3 Answers3

4

If you want to use $ in a replacement string you need to escape it using $$. The $ character is used as a backreference:

var a,
    b,
    c;
a = "$$&";
b = "aba";
c = b.replace(/a/, a);
console.log(c); //$&ba

If you want to replace all instances of a pattern in a string, you need to mark the regular expression as being global:

var a,
    b,
    c;
a = "$$&";
b = "aba";
c = b.replace(/a/g, a);
console.log(c); //$&b$&
zzzzBov
  • 174,988
  • 54
  • 320
  • 367
  • Thanks, for your answer. Is there a way to esacepe the `$` in an other way than doing this manually? E.g. if the content in variable `a` is loaded from an external ressource. – Patrick Schmidt Oct 12 '12 at 20:01
  • 1
    @PatrickSchmidt, certainly, use a regex replace! `a = a.replace(/\$/g, '$$$$');`. – zzzzBov Oct 12 '12 at 20:04
  • The linked documentation is specific to Firefox, though, and the OP said that the browser is Chrome. The docs are relevant on this particular topic, but not everything on the linked article will work in Chrome. (just sayin') – JDB Oct 12 '12 at 20:04
  • Alternatively, if you're worried about how all those `$` characters look, you could use `String.prototype.split` in conjunction with `Array.prototype.join`: `a = a.split('$').join('$$');` – zzzzBov Oct 12 '12 at 20:05
  • @Cyborgx37, MDN's wiki-based documentation is known for being pretty cross-browser compatible. – zzzzBov Oct 12 '12 at 20:06
2

The $ is a backreference character. It has special meaning in the replace string.

See this related question:
JavaScript - string regex backreferences

Or, more helpfully, visit this page for more detailed documentation:
http://www.regular-expressions.info/javascript.html#replace

To fix your replacement, try:

var a = "$$&";
var b = "aba";

var c = b.replace(/a/g, a);

EDIT: Forgot about the global replace character. Added.

Community
  • 1
  • 1
JDB
  • 25,172
  • 5
  • 72
  • 123
0

Two isues:

(1) If you want to replace all occurrences, then you need to use /g modifier

(2) String $& in regex has meaning of pattern match, so you were replacing match by itself

Put it together you need to modify your code by escaping dollar sign by another one... >>

var a = "$$&"; 
var b = "aba"; 
var c = b.replace(/a/g, a);
Ωmega
  • 42,614
  • 34
  • 134
  • 203