Template literal inside of the RegEx

Solution 1:

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);