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


当前回答

我也遇到过这样的问题。我有一个URL,我想检查链接是否以图像格式或其他文件格式结束,有一个图像格式数组。以下是我所做的:

const imagesFormat = ['.jpg','.png','.svg']
const link = "https://res.cloudinary.com/***/content/file_padnar.pdf"
const isIncludes = imagesFormat.some(format => link.includes(format))
    
// false

其他回答

借鉴T.J. Crowder的解决方案,我创建了一个原型来处理这个问题:

Array.prototype.check = function (s) {
  return this.some((v) => {
    return s.indexOf(v) >= 0;
  });
};

以下是目前为止(在我看来)最好的解决方案。这是一个现代的(ES6)解决方案,它:

是高效的(一行!) 避免for循环 与其他答案中使用的some()函数不同,这个函数不仅返回一个布尔值(true/false) 相反,它要么返回子字符串(如果它在数组中找到),要么返回undefined 更进一步,允许您选择是否需要部分子字符串匹配(示例如下)

享受吧!



const arrayOfStrings = ['abc', 'def', 'xyz'];
const str = 'abc';
const found = arrayOfStrings.find(v => (str === v));

在这里,found将被设置为'abc'。这将适用于精确的字符串匹配。

如果你用:

const found = arrayOfStrings.find(v => str.includes(v));

同样,found在本例中被设置为'abc'。这不允许部分匹配,所以如果str被设置为'ab', found将是未定义的。


And, if you want partial matches to work, simply flip it so you're doing:
const found = arrayOfStrings.find(v => v.includes(str));

代替。如果str被设为'ab' found就会被设为'abc'

容易peasy !



你可以这样检查:

<!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>

Javascript函数使用搜索字符串或搜索字符串数组搜索标签或关键字数组。(使用ES5的一些数组方法和ES6的箭头函数)

// returns true for 1 or more matches, where 'a' is an array and 'b' is a search string or an array of multiple search strings
function contains(a, b) {
    // array matches
    if (Array.isArray(b)) {
        return b.some(x => a.indexOf(x) > -1);
    }
    // string match
    return a.indexOf(b) > -1;
}

使用示例:

var a = ["a","b","c","d","e"];
var b = ["a","b"];
if ( contains(a, b) ) {
    // 1 or more matches found
}

使用underscore.js或lodash.js,你可以对字符串数组执行以下操作:

var contacts = ['Billy Bob', 'John', 'Bill', 'Sarah'];

var filters = ['Bill', 'Sarah'];

contacts = _.filter(contacts, function(contact) {
    return _.every(filters, function(filter) { return (contact.indexOf(filter) === -1); });
});

// ['John']

在一个字符串上:

var contact = 'Billy';
var filters = ['Bill', 'Sarah'];

_.every(filters, function(filter) { return (contact.indexOf(filter) >= 0); });

// true