I'm trying to search a string and find multiple matches at once from an array.
I joined my array items with '|', but I'm getting null.
var searchTerms = ['dog', 'cat'];
var str = 'I have a dog and a cat';
// want to return matches for both dog and cat
console.log(str.match('/' + searchTerms.join('|') + '/g'));
http://jsfiddle.net/duDP9/1/
Use RegExp like this:
var searchTerms = ['dog', 'cat'];
var str = 'I have a dog and a cat';
console.log(str.match(new RegExp(searchTerms.join('|'), 'g')));
You could also use Array.every(), along with Str.indexOf, which returns -1 if the string isn't found:
var searchTerms = ['dog', 'cat'];
var str = 'I have a dog and a cat';
searchTerms.every(search => str.indexOf(search) !== -1);
// true
str = 'I only have a dog';
searchTerms.every(search => str.indexOf(search) !== -1);
// false
Array.every returns true if the callback returns true for every element of the array.
The advantage of using this approach over regular expressions is that there is less chance that characters in your searchTerms will be interpreted in unexpected ways.
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