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


当前回答

var str = "A for apple" var subString = ["apple"] console.log (str.includes (subString))

其他回答

最好的答案是: 这也是不区分大小写的

    var specsFilter = [.....];
    var yourString = "......";

    //if found a match
    if (specsFilter.some((element) => { return new RegExp(element, "ig").test(yourString) })) {
        // do something
    }
substringsArray.every(substring=>yourBigString.indexOf(substring) === -1)

全力支持;)

我并不是建议你去扩展/修改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

如果数组不大,可以使用indexOf()循环并逐个检查每个子字符串。或者,您可以构造一个带有子字符串作为替代的正则表达式,这可能更有效,也可能不更有效。

对于用谷歌搜索的人来说,

确切的答案应该是。

const substrings = ['connect', 'ready'];
const str = 'disconnect';
if (substrings.some(v => str === v)) {
   // Will only return when the `str` is included in the `substrings`
}