1

I am not able to create a regex from a variable, using template literals

What is wrong and how to fix it?

const myValue = 'a.b'
const reg = new RegExp(`/^${myValue}$/`);
/*
  /^a.b/
*/
RaJesh RiJo
  • 4,102
  • 4
  • 20
  • 45
GibboK
  • 68,054
  • 134
  • 405
  • 638

1 Answers1

3

Remove the slashes from the template literal. Slashes inside the string are escaped by the constructor, and included as part of the pattern.

const myValue = 'a.b'
const reg = new RegExp(`^${myValue}$`);
/*
  /^a.b$/
*/

console.log(reg);
Ori Drori
  • 166,183
  • 27
  • 198
  • 186