Reputation: 561
What is the most efficient way to find out if a JavaScript array contains substring of a given string?
For example in case I have a JavaScript array
var a = ["John","Jerry","Ted"];
I need the condition which returns true
when I compare the above array against the string:
"John Elton"
Upvotes: 0
Views: 125
Reputation: 4147
In case you cannot use ES6:
let arr = ["John","Jerry","Ted"];
let str = "John Elton";
var match = arr.some(function (name) {
return str.indexOf(name) > -1;
});
console.log(match);
Upvotes: 0
Reputation: 2127
For ES6:
var array = ["John","Jerry","Ted"];
var strToMatch = "John Elton"
array.some(el => strToMatch.includes(el))
Upvotes: 4
Reputation: 39322
You can use .some()
and .includes()
methods:
let arr = ["John","Jerry","Ted"];
let str = "John Elton";
let checker = (arr, str) => arr.some(s => str.includes(s));
console.log(checker(arr, str));
Upvotes: 4