javascriptescapingbackreference

Javascript Regex Replace Without Resolving Backreference


I'm trying to replace a password token [**PASSWORD**] in a string with the password and am having trouble with passwords that contain the string $&.

For example:

var re = new RegExp('(?:\\[\\*\\*PASSWORD\\*\\*\\])', 'g');
'Your temporary password is: [**PASSWORD**]'.replace(re, 'B9z3$&dd');

I want the output to be Your temporary password is: B9z3$&dd, but instead the $& is resolving the backreference to [**PASSWORD**] which makes the output Your temporary password is: B9z3[**PASSWORD**]dd

How can I prevent Javascript from resolving the backreference and simply insert the text as-is?

Thank you!


Solution

  • You need to escape the $ in your replacement string doubling it: B9z3$$&dd.

    Here's a demo:

    result = 'Your temporary password is: [**PASSWORD**]'.replace(/\[\*\*PASSWORD\*\*\]/mg, "B9z3$$&dd");
    
    console.log(result);