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
  • 3,872
  • 4
  • 18
  • 44
GibboK
  • 64,078
  • 128
  • 380
  • 620

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
  • 145,770
  • 24
  • 170
  • 162