简体   繁体   English

如何检查字符串是否包含JavaScript中预定义数组中存在的子字符串?

[英]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? 找出JavaScript数组是否包含给定字符串的子字符串的最有效方法是什么?

For example in case I have a JavaScript array 例如,如果我有一个JavaScript数组

var a = ["John","Jerry","Ted"];

I need the condition which returns true when I compare the above array against the string: 我需要将上述数组与字符串进行比较时返回true的条件:

"John Elton"

You can use .some() and .includes() methods: 您可以使用.some().includes()方法:

 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: 对于ES6:

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

In case you cannot use ES6: 万一您不能使用ES6:

 let arr = ["John","Jerry","Ted"]; let str = "John Elton"; var match = arr.some(function (name) { return str.indexOf(name) > -1; }); console.log(match); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何检查一个字符串在JavaScript中是否包含一个substring? - How to check whether a string contains a substring in JavaScript? 如何在 JavaScript(打字稿)中检查字符串是否包含 substring? - How to check whether a string contains a substring in JavaScript(typescript)? 如何检查字符串是否包含JavaScript中的字符串数组中的子字符串 - how to check if a string contains a substring from an array of strings in JavaScript 如何检查具有更多单词的字符串是否包含 JavaScript 中具有更多单词的 substring? - How to check whether a string with more words contains a substring with more words in JavaScript? 如何检查字符串是否包含子字符串并在javascript中为其着色? - how to check if a string contains substring and color it in javascript? 如何在JavaScript中检查字符串是否包含子字符串 - How to check string contains substring in javascript 检查字符串是否包含JavaScript中的子字符串 - Check string contains substring in javascript 检查字符串数组是否包含javascript中给定字符串的子字符串? - Check if an array of strings contains a substring of a given string in javascript? 如何检查 object 的数组是否存在于 Javascript 的另一个 object 数组中 - How to check whether an array of object is present in another array of object in Javascript 使用should.js如何检查数组中是否存在字符串? - Using should.js how to check whether a string is not present in an array?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM