很直接。在 javascript 中,我需要检查一个字符串是否包含数组中保存的任何子字符串。
没有任何内置功能可以为您做到这一点,您必须为它编写一个函数,尽管它可以只是对some数组方法的回调。
some
两种方法供您使用:
数组some方法(在 ES5 中添加)使这非常简单:
if (substrings.some(function(v) { return str.indexOf(v) >= 0; })) { // There's at least one }
使用箭头函数和新includes方法(ES2015+)更好:
includes
if (substrings.some(v => str.includes(v))) { // There's at least one }
现场示例:
const substrings = ["one", "two", "three"]; let str; // Setup console.log(`Substrings: ${substrings}`); // Try it where we expect a match str = "this has one"; if (substrings.some(v => str.includes(v))) { console.log(`Match using "${str}"`); } else { console.log(`No match using "${str}"`); } // Try it where we DON'T expect a match str = "this doesn't have any"; if (substrings.some(v => str.includes(v))) { console.log(`Match using "${str}"`); } else { console.log(`No match using "${str}"`); }
如果您 知道 字符串不包含任何正则表达式中的特殊字符,那么您可以作弊,如下所示:
if (new RegExp(substrings.join("|")).test(string)) { // At least one match }
…创建一个正则表达式,它是您要查找的子字符串的一系列 交替 (例如,one|two)并测试是否有匹配的任何一个,但如果任何子字符串包含任何特殊字符在正则表达式(*,[等)中,您必须先将它们转义,并且最好只做无聊的循环。有关逃避它们的信息,请参阅此问题的答案。
one|two
*
[
const substrings = ["one", "two", "three"]; let str; // Setup console.log(`Substrings: ${substrings}`); // Try it where we expect a match str = "this has one"; if (new RegExp(substrings.join("|")).test(str)) { console.log(`Match using "${str}"`); } else { console.log(`No match using "${str}"`); } // Try it where we DON'T expect a match str = "this doesn't have any"; if (new RegExp(substrings.join("|")).test(str)) { console.log(`Match using "${str}"`); } else { console.log(`No match using "${str}"`); }