Reputation: 9753
I want to check if there are two or more values in a string, regardless of their positions within said string. For example, if I want a condition of "OR" in regex, I would do so:
/(a|b)/.test("a") // true
But what I need is an "AND"; something like this:
/(a&b)/.test("a") // false
/(a&b)/.test("b") // false
/(a&b)/.test("a b") // true
/(b&a)/.test("a b") // true
/(a&b&c)/.test("a b") // false
/(a&b&c)/.test("a c b") // true
Obviously this syntax is not correct...
These values a
, b
, c
, etc. are pulled from an array. I've tried using a combination of eval()
and indexOf(a) !== -1 && indexOf(b) !== -1
but that was too slow, which is why I'm turning to regexes.
Upvotes: 2
Views: 1799
Reputation: 85478
Since you're matching fixed strings, you could just use:
function matchAll(str, arr)
{
for (var i=0; i<arr.length; ++i) {
if (str.indexOf(arr[i]) === -1) {
return false;
}
}
return true;
}
matchAll('a', ['a']); // true
matchAll('a', ['a', 'b']); // false
matchAll('a b', ['a', 'b']); // true
matchAll('a b c', ['a', 'b']); // true
matchAll('a b', ['a', 'b', 'c']); // false
matchAll('a c b', ['a', 'b', 'c']); // true
matchAll('c a b', ['a', 'b', 'c']); // true
If you're looking for fixed strings, .indexOf()
will be faster than regexes.
Upvotes: 1
Reputation: 8994
The answer @OmarJackman posted will do what you're asking for. However, it's worth noting that his solution uses lookarounds which require more processing than simpler regexes. If you're looking for good performance I'd recommend that you just run two separate regexes (test for case a
and then for case b
). Two simple regexes will run orders of magnitude faster than one complex one, especially as the search text becomes larger.
Edit: As noted in the comments, "orders of magnitude" is an unfair exaggeration of the performance impact, but performance should be considered regardless.
Upvotes: 1