非常直截了当。在javascript中,我需要检查字符串是否包含数组中持有的任何子字符串。


当前回答

我并不是建议你去扩展/修改String的原型,但这是我所做的:

String.prototype.includes ()

String.prototype.includes = function (includes) { console.warn("String.prototype.includes() has been modified."); return function (searchString, position) { if (searchString instanceof Array) { for (var i = 0; i < searchString.length; i++) { if (includes.call(this, searchString[i], position)) { return true; } } return false; } else { return includes.call(this, searchString, position); } } }(String.prototype.includes); console.log('"Hello, World!".includes("foo");', "Hello, World!".includes("foo") ); // false console.log('"Hello, World!".includes(",");', "Hello, World!".includes(",") ); // true console.log('"Hello, World!".includes(["foo", ","])', "Hello, World!".includes(["foo", ","]) ); // true console.log('"Hello, World!".includes(["foo", ","], 6)', "Hello, World!".includes(["foo", ","], 6) ); // false

其他回答

function containsAny(str, substrings) {
    for (var i = 0; i != substrings.length; i++) {
       var substring = substrings[i];
       if (str.indexOf(substring) != - 1) {
         return substring;
       }
    }
    return null; 
}

var result = containsAny("defg", ["ab", "cd", "ef"]);
console.log("String was found in substring " + result);
var str = "texttexttext";
var arr = ["asd", "ghj", "xtte"];
for (var i = 0, len = arr.length; i < len; ++i) {
    if (str.indexOf(arr[i]) != -1) {
        // str contains arr[i]
    }
}

编辑: 如果测试的顺序不重要,你可以使用这个(只有一个循环变量):

var str = "texttexttext";
var arr = ["asd", "ghj", "xtte"];
for (var i = arr.length - 1; i >= 0; --i) {
    if (str.indexOf(arr[i]) != -1) {
        // str contains arr[i]
    }
}
substringsArray.every(substring=>yourBigString.indexOf(substring) === -1)

全力支持;)

基于t。j。克劳德的答案

使用转义的RegExp测试至少一个子字符串的“至少一次”出现。

函数buildSearch(substrings) { 返回新的RegExp( 子字符串 . map(函数(s) {s.replace返回 (/[.*+?^${}()|[\]\\]/ g , '\\$&');}) .join('{1,}|') + '{1,}' ); } var pattern = buildSearch(['hello','world']); console.log(模式。测试('你好')); console.log(模式。Test ('what a wonderful world')); console.log(模式。Test ('my name is…'));

const str = '此字符串是否包含下面数组中的一个或多个字符串?'; Const arr = ['one', 'two', 'three']; Const包含= arr。Some (element => { If (str.includes(element)) { 返回true; } 返回错误; }); console.log(包含);/ /正确的