Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template Literals with Javascript Replace? [duplicate]

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.

like image 480
chobo2 Avatar asked Feb 06 '26 20:02

chobo2


1 Answers

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)
like image 154
lenilsondc Avatar answered Feb 09 '26 12:02

lenilsondc