Reputation:
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
Reputation: 627022
You can use the array of values to build a dynamic regex:
.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
alternation operatorString#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