0

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"
3

3 Answers 3

4

For ES6:

var array = ["John","Jerry","Ted"];
var strToMatch = "John Elton"
array.some(el => strToMatch.includes(el))
Sign up to request clarification or add additional context in comments.

Comments

4

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));

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.