问题
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, \'\');
})
}
回答1:
Your regex
variable is a String. To make it a RegExp, 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);
来源:https://stackoverflow.com/questions/43390873/template-literal-inside-of-the-regex