Home > other >  How to use JavaScript replace() without triggering the special replacement patterns?
How to use JavaScript replace() without triggering the special replacement patterns?

Time:01-17

I'm trying to inject some code into a file by using replace. The problem is if the target code contains any of the replace() function's special character sequences, namely $$, it will do something different than what I expect, which is to just copy the characters exactly as they are.

'replaceme'.replace('replaceme', '$$');

you would think this would result in $$ but it actually returns $

Is there a way to disable this functionality so that it maintains the $$ like I want?

CodePudding user response:

No idea why the $$ wasn't working, I too am wondered. But you can get the result by using the callback function.

'replaceme'.replace('replaceme', () => '$$');

CodePudding user response:

If you do not like to apply the replacement string patterns, you can use a replacement function:

'replaceme'.replace('replaceme', (_match) => '$$');

CodePudding user response:

This might be a bit hacky, but you can create a new method on String that replaces all $ characters in the replacement string with $$:

function replaceRaw(original, match, text) {
  text = text.replaceAll('$', '$$$$');
  return original.replace(match, text);
}

console.log(replaceRaw('replaceme', 'replaceme', '$$'));

Note that $$ in the replacement text will become a single $, so this new method makes all $s in the replace $$ (see this MDN article).

  • Related