Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Regex Match All from Array

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/


2 Answers

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')));
like image 158
friedi Avatar answered Nov 26 '25 07:11

friedi


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.

like image 36
Tom Fenech Avatar answered Nov 26 '25 07:11

Tom Fenech



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!