当参数包含多个需要转义的simbols时,是否可以转义参数化正则表达式?
const _and = '&&', _or = '||';
let reString = `^(${_and}|${_or})`; //&{_or} needs to be escaped
const reToken = new RegExp(reString);
有效但不是最佳的:
_or = '\|\|';
或:
let reString = `^(${_and}|\|\|)`;
最好重用_or
变量并保持正则表达式参数化。
您可以创建自己的函数来转义您的参数,以便这些函数在最终正则表达式中工作。为了节省您的时间,我已经找到了一个写在这个答案中。使用该函数,您可以编写干净的参数,而无需手动转义所有内容。虽然我会避免修改类中的构建(RegExp(并围绕它或单独的东西做一个包装器。在下面的示例中,我使用了我在另一个答案中找到的确切函数,它扩展了 RegExp 中的构建。
RegExp.escape = function(s) {
return s.replace(/[-/\^$*+?.()|[]{}]/g, '\$&');
};
const and = RegExp.escape('&&');
const or = RegExp.escape('||');
const andTestString = '1 && 2';
const orTestString = '1 || 2';
const regexp = `${and}|${or}`;
console.log(new RegExp(regexp).test(andTestString)); // true
console.log(new RegExp(regexp).test(orTestString)); // true
编辑https://jsfiddle.net/ao4t0pzr/1/
您可以使用模板文本函数通过正则表达式转义字符串中的字符。然后,您可以使用该字符串传播填充有转义字符的新正则表达式:
function escape(s) {
return s[0].replace(/[-&/\^$*+?.()|[]{}]/g, '\$&');
};
var or = escape`||`;
var and = escape`&&`;
console.log(new RegExp(`${and}|${or}`)); // "/&&|||/"