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.