user3448187
user3448187

Reputation:

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/

Upvotes: 3

Views: 1617

Answers (5)

Tom Fenech
Tom Fenech

Reputation: 74705

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.

Upvotes: 2

friedi
friedi

Reputation: 4360

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')));

Upvotes: 5

p.s.w.g
p.s.w.g

Reputation: 149108

If you want to dynamically create a RegExp object from a string you need to use the constructor:

console.log(str.match(new RegExp(searchTerms.join('|'), 'g')));

However, I'd generally recommend some other approach. If your search terms contain a special regex character (e.g. $), then this is likely to fail. Of course you could escape those special characters, but still, I'd recommend you look for some other solution if possible.

It's hard to say exactly what solution would look like, since I don't know the full use case, but here's a very simple example of an alternative solution:

var str = 'I have a dog and a cat';
var searchTerms = {'dog': 1, 'cat': 1};
console.log(str.split(/\s+/).filter(function(x) { return x in searchTerms; }));
// [ "dog", "cat" ]

Upvotes: 1

Javier Diaz
Javier Diaz

Reputation: 1830

The syntax of what you want to do is (option1|option2|...|optionN) watch out the parentheses, I don't think you've added them.

Try to use: console.log(str.match('/(' + searchTerms.join('|') + ')/g'));

Upvotes: 0

falsetru
falsetru

Reputation: 369494

You need to convert the string to regular expression using new RegExp(..., 'g')

console.log(str.match(new RegExp(searchTerms.join('|'), 'g')));

Upvotes: 1

Related Questions