What is the most concise and efficient way to translate an array of strings in a regex and then use the regex multiple times on different strings to get the result matches and then iterate over them? Now I'm using the following:
var myArray = ['peaches', 'bananas', 'papaya', 'supercity'];
var myString = 'I want some papaya and some peaches';
var regexFromMyArray = new RegExp(myArray.toString().replace(/,/g, '|'), 'gi');
var matches = myString.match(regexFromMyArray) || [];
if (matches.length) {
for (var i = 0, l = matches.length; i < l; i++) {
console.log('Found: ' + matches[i]);
}
}
performance is important here, so plain javascript please.
Just join with pipeline, using Array.join
var regexFromMyArray = new RegExp(myArray.join("|"), 'gi');
and just do this as if
condition is just redundant.
for(var i = 0; i < matches.length; i++)
console.log("Found:", matches[i]);
toString
internally calls join(",")
) and replace
function is also not used.And since you talk about regexes, I'd like to say that
String.indexOf
, which is a non-regex form of solving the same.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With