2

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.

chobo2
  • 79,578
  • 183
  • 505
  • 811

2 Answers2

6

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)
lenilsondc
  • 9,162
  • 1
  • 23
  • 38
  • I found one interesting video explaining ES6 template literals here : https://www.youtube.com/watch?v=asRu9MPojFE – Milap Aug 25 '21 at 08:50
1

How about constructing the pattern as string using the template literals first and then create regex pattern from the string?

const regex = "~!@#$%&*()_^" ;
const data = "$88.10";
// suppose you want to remove these characters from the string
const result = data.replace(new RegExp(`[${regex}]`, 'gi'), '');

console.log(result)
Psidom
  • 195,464
  • 25
  • 298
  • 322