Basj
Basj

Reputation: 46229

Check if a string contains a token from a list, with Javascript

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

Answers (2)

Bergi
Bergi

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

bowheart
bowheart

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

Related Questions