没有内置功能可以为您做到这一点,您必须为其编写一个函数。
如果您 知道 字符串不包含任何正则表达式中特殊的字符,那么您可以作弊一点,如下所示:
if (new RegExp(substrings.join("|")).test(string)) { // At least one match}…这会创建一个正则表达式,该正则表达式是您要查找的子字符串(例如)的一系列 替换
,
one|two并测试是否有匹配的子字符串,但是如果任何子字符串包含任何特殊字符在正则表达式(
*,
[等)中,您必须先将其转义,最好只进行无聊的循环。
现场示例:
var substrings = ["one", "two", "three"];var str;// Setupconsole.log("Substrings: " + substrings.join(","));// Try it where we expect a matchstr = "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 matchstr = "this doesn't have any";if (new RegExp(substrings.join("|")).test(str)) { console.log("Match using '" + str + "'");} else { console.log("No match using '" + str + "'");}在对该问题的评论中,Martin询问了
Array.prototype.mapECMAscript5中的新方法。
map并没有太多帮助,但是
some:
if (substrings.some(function(v) { return str.indexOf(v) >= 0; })) { // There's at least one}现场示例:
var substrings = ["one", "two", "three"];var str;// Setupconsole.log("Substrings: " + substrings.join(","));// Try it where we expect a matchstr = "this has one";if (substrings.some(function(v) { return str.indexOf(v) >= 0; })) { console.log("Match using '" + str + "'");} else { console.log("No match using '" + str + "'");}// Try it where we DON'T expect a matchstr = "this doesn't have any";if (substrings.some(function(v) { return str.indexOf(v) >= 0; })) { console.log("Match using '" + str + "'");} else { console.log("No match using '" + str + "'");}尽管对polyfill来说是微不足道的,但您只能在符合ECMAscript5的实现中使用它。
2020年更新 :
some带有箭头功能(ES2015 +)的示例可能更简单,您可以使用
includes而不是
indexOf:
if (substrings.some(v => str.includes(v))) { // There's at least one}现场示例:
const substrings = ["one", "two", "three"];let str;// Setupconsole.log("Substrings: " + substrings.join(","));// Try it where we expect a matchstr = "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 matchstr = "this doesn't have any";if (substrings.some(v => str.includes(v))) { console.log("Match using '" + str + "'");} else { console.log("No match using '" + str + "'");}甚至扔掉
bind它,尽管对我来说箭头功能更具可读性:
if (substrings.some(str.includes.bind(str))) { // There's at least one}现场示例:
const substrings = ["one", "two", "three"];let str;// Setupconsole.log("Substrings: " + substrings.join(","));// Try it where we expect a matchstr = "this has one";if (substrings.some(str.includes.bind(str))) { console.log("Match using '" + str + "'");} else { console.log("No match using '" + str + "'");}// Try it where we DON'T expect a matchstr = "this doesn't have any";if (substrings.some(str.includes.bind(str))) { console.log("Match using '" + str + "'");} else { console.log("No match using '" + str + "'");}


