RegEx内部的模板文字 [英] Template literal inside of the RegEx
问题描述
我尝试在RegEx中放置模板文字,但它不起作用。然后我创建了一个变量 regex
,它保存了我的RegEx,但它仍然没有给我所需的结果。
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.
但是如果我单独 console.log(正则表达式)
,我会收到所需的RegEx,例如 /.+?(?= location)/ i
, /.+?(?= date)/ i
依此类推,但一旦我放置 regex
在 .replace
内,它似乎无法正常工作
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, '');
})
}
推荐答案
您的正则表达式
变量是 String 。要使它成为RegExp,请使用
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);
这篇关于RegEx内部的模板文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!