user4479529
user4479529

Reputation:

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

I have written a node module with several places that use regular expressions to limit which files are manipulated as below:

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

I'm trying to modify the module to accept user input as an array - i.e.:

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

Is there a good way to convert the array into the regex? I know apply might work if I wasn't using file.match but I'm not sure if it will work in this instance. Thanks in advance.

Upvotes: 0

Views: 349

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627022

You can use the array of values to build a dynamic regex:

  • Escape all special regex characters with .replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
  • Build the regex with the help of | alternation operator
  • Use the regex with String#match or RegExp#exec methods.

Here is a working snippet:

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!");
}

Upvotes: 1

Related Questions