JavaScript/node.js将数组转换为正则表达式.匹配if语句的参数

JavaScript/node.js convert array into regex.match arguments for if statement

本文关键字:匹配 正则表达式 if 语句 参数 转换 node js 数组 JavaScript      更新时间:2023-09-26

我已经编写了一个节点模块,其中有几个地方使用正则表达式来限制要操作的文件,如下所示:

if (!file.match(/'/node_modules'//) && !file.match(/'/fontawesome'//) && !file.match(/'/docs'//) && !file.match(/'/target'//) && !seenFile[file]) {
    //do some processing
}

我正在尝试修改模块,以接受作为数组的用户输入,即:

['/node_modules/', '/fontawesome/', '/docs/', '/target/']

有没有一种好的方法可以将数组转换为正则表达式?我知道如果我不使用file.match,apply可能会起作用,但我不确定它在这种情况下是否会起作用。提前谢谢。

您可以使用值数组来构建动态正则表达式:

  • .replace(/[.*+?^${}()|[']'']/g, "''$&");转义所有特殊正则表达式字符
  • 借助|交替运算符构建正则表达式
  • 将正则表达式与String#matchRegExp#exec方法一起使用

以下是一个工作片段:

var ar = ['/node_modules/', '/fontawesome/', '/docs/', '/target/'];
ar = ar.map(function(item) {  
          return item.replace(/[.*+?^${}()|[']'']/g, "''$&");
       });
var rx = RegExp(ar.join("|"));
var file = "/node_modules/d.jpg";
if (!file.match(rx)) {
    console.log("No stop words found!");
} else {
    console.log("Stop words found!");
}