0

I have a string with indexes $1 and I would like to replace them with values. Something like this:

const index = 1; // This is dynamic, so we need to use this index variable

let myStr = 'Hi there $1';
myStr = myStr.replace(/\$1/g, 'FRIEND');
console.log(myStr); // Hi there FRIEND

The above works, but now I need to replace the 1 with index:

const index = 1; // This is dynamic, so we need to use this index variable
let myStr = 'Hi there $1';
myStr = myStr.replace(new RegExp('$' + index, 'g'), 'FRIEND');
myStr = myStr.replace(new RegExp('\$' + index, 'g'), 'FRIEND');
console.log(myStr);

Neither of the above ideas work? I can use a substring solution, but I was hoping String.replace() would be useable.

Paul Kruger
  • 2,094
  • 7
  • 22
  • 49
  • An unescaped `$` means "End of string" in a regular expression - you must escape it with a literal backslash passed to the constructor (which requires 2 typed backslashes, if using anything other than `String.raw`) – CertainPerformance Oct 28 '19 at 05:36
  • That is definitely not a duplicate question. How would I ever google `Why do regex constructors need to be double escaped?` when I don't even know that is the answer to my question...but thank you it did solve my question – Paul Kruger Oct 28 '19 at 05:54

0 Answers0