Suraj Nair
Suraj Nair

Reputation: 561

How to check whether a string contains a substring which is present in a predefined array in JavaScript?

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

Answers (3)

Davi
Davi

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

Stephen.W
Stephen.W

Reputation: 2127

For ES6:

var array = ["John","Jerry","Ted"];
var strToMatch = "John Elton"
array.some(el => strToMatch.includes(el))

Upvotes: 4

Mohammad Usman
Mohammad Usman

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

Related Questions