Looking for a generic solution, I obtained the following:
var input = prompt( 'Enter input:' ) || '';
var result = 'foo X bar X baz'.replace( /X/g, input.replace( /\$/g, '$$$$' ) );
It works:
input: $$
result: foo $$ bar $$ baz
input: $&
result: foo $& bar $& baz
But it's a bit tricky, because of the multi-level $
escaping. See that $$$$
in the inner replace
...
So, I tried using a callback, to which special replacement patterns aren't applied:
var result = 'foo X bar X baz'.replace( /X/g, function () {
var input = prompt( 'Enter input:' ) || '';
return input;
} );
It works too, but has a caveat: the callback is executed for each replacement. So in the above example, the user is prompted twice...
Finally, here is the fixed code for the "callback" solution, by moving the prompt out of the replace callback:
var input = prompt( 'Enter input:' ) || '';
var result = 'foo X bar X baz'.replace( /X/g, function () {
return input;
} );
To summarize, you have two solutions:
- Apply a
.replace(/\$/g, '$$$$')
escaping on the replacement string
- Use a callback, which does nothing more than just returning the replacement string
MDN reference: String.prototype.replace()#Description