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"
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));
For ES6:
var array = ["John","Jerry","Ted"];
var strToMatch = "John Elton"
array.some(el => strToMatch.includes(el))
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.