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,302
  • 4
  • 25
  • 46
GibboK
  • 71,848
  • 143
  • 435
  • 658

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
  • 183,571
  • 29
  • 224
  • 209