Reputation: 46229
I want to check if a string s
contains any of the tokens in the list L
.
Is there a built-in function in Javascript for this? or do I have to do it manually with something like:
function present(s, L) {
for (var i = 0; i < L.length; i++)
if (s.indexOf(L[i]) !== -1)
return true;
return false;
}
var L = ['abc', 'def', 'ghi'];
var s = 'Yes, definitely.';
present(s, L); // true
Upvotes: 2
Views: 1732
Reputation: 665020
You can simplify your loop with the some
higher-order function, and use includes
instead of indexOf
:
L.some(token => s.includes(token))
Upvotes: 5
Reputation: 4676
You can just create a Regular Expression with all the items in list
by sticking a |
operator between each of them. Then use RegExp.prototype.test() to check for a match:
function isPresent(string, list) {
return new RegExp(list.join('|')).test(string)
}
var list = ['abc', 'def', 'ghi'];
var string = 'Yes, definitely.';
isPresent(string, list); // true
Upvotes: 1