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


当前回答

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

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

    //if found a match
    if (specsFilter.some((element) => { return new RegExp(element, "ig").test(yourString) })) {
        // do something
    }

其他回答

单线解决方案

substringsArray.some(substring=>yourBigString.includes(substring))

如果子字符串存在\不存在,则返回true\false

需要ES6支持

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);

你可以这样检查:

<!DOCTYPE html>
<html>
   <head>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
      <script>
         $(document).ready(function(){
         var list = ["bad", "words", "include"] 
         var sentence = $("#comments_text").val()

         $.each(list, function( index, value ) {
           if (sentence.indexOf(value) > -1) {
                console.log(value)
            }
         });
         });
      </script>
   </head>
   <body>
      <input id="comments_text" value="This is a bad, with include test"> 
   </body>
</html>

基于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…'));

let obj = [{name : 'amit'},{name : 'arti'},{name : 'sumit'}];
let input = 'it';

使用滤镜:

obj.filter((n)=> n.name.trim().toLowerCase().includes(input.trim().toLowerCase()))