0

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.

4
  • Just trying to figure out what you need: is this code of any help? Commented Nov 2, 2015 at 20:51
  • Thanks, that was a big help. I was confused about || in js vs. | in regex. Commented Nov 2, 2015 at 21:52
  • So, can I post it as an answer? I think there is one mistake: RegExp(rx) must be used. Commented Nov 2, 2015 at 21:53
  • 1
    Please do. I'll will mark it as correct. Commented Nov 2, 2015 at 21:57

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.