Template literal inside of the RegEx

camelCaseVlad picture camelCaseVlad · Apr 13, 2017 · Viewed 26k times · Source

I tried to place a template literal inside of a RegEx, and it didn't work. I then made a variable regex which holds my RegEx, but it still not giving me the desired result.

However if I console.log(regex) individually, I do receive the desired RegEx, such as /.+?(?=location)/i, /.+?(?=date)/i and so on, but once I place regex inside the .replace it appears not to be working

function validate (data) {
  let testArr = Object.keys(data);
  errorMessages.forEach((elem, i) => {
    const regex = `/.+?(?=${elem.value})/i`;
    const a = testArr[i].replace(regex, '');
    })
  }

Answer

Wiktor Stribiżew picture Wiktor Stribiżew · Apr 13, 2017

Your regex variable is a String. To make it a RegExp, use a RegExp constructor:

const regex = new RegExp(String.raw`pattern_as_in_regex_literal_without_delimiters`)

For example, a regex literal like /<\d+>/g can be re-written as

const re = RegExp(String.raw`<\d+>`, 'g') // One \ is a literal backslash
const re = RegExp(`<\\d+>`, 'g')       // Two \ are required in a non-raw string literal

To insert a variable you may use

const digits = String.raw`\d+`;
const re = RegExp(`<${digits}>`, 'g')

To solve your issue, you may use

const regex = new RegExp(`.+?(?=${elemvalue.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')})`, "i"); 

Also, it is a good idea to escape the variable part in the regex so as all special regex metacharacters were treated as literals.

const s = "final (location)";
const elemvalue = "(location)";
const regex = new RegExp(`.+?(?=${elemvalue.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')})`, "i");
// console.log(regex); // /.+?(?=\(location\))/i
// console.log(typeof(regex)); // object
let a = s.replace(regex, '');
console.log(a);