am I able to use template literals with javascript replace regex?
I have something like this
const regex = "~!@#$%^&*()_" ;
const data = "$88.10";
const result = data.replace(`[^${regex}/gi]$`, '');
nothing is getting stripped though, so not sure if I just messed the format.
am I able to use template literals with javascript replace regex?
With regex literal (i.e., /^(.*)&/g) you can't. Template literals are meant to build strings, regex literals are not strings.
What you can do is use template literal to build the regex's pattern like bellow:
const regex = "~!@#$%^&*()_" ;
const data = "$88.10";
const pattern = `[^${regex}/gi]$`;
const result = data.replace(new RegExp(pattern, 'g'), '');
Alternatively you can create a Tagged template to build the regex for you like:
rgx`[${regex}]` // returns new RegExp('..
For example:
// tagged template function
function rgx(str0, str1){
return new RegExp(`${str0.raw[0]}${str1}${str0.raw[1]}`, 'gi')
}
const regex = "~!@#$%^&*()_" ;
const data = "$88.10";
const result = data.replace(rgx`[${regex}]`, '');
console.log(result)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With