如何检查字符串中是否存在数组值之一?

问题描述 投票:0回答:1

我有三种类型的字符串。

This is a test.

I am testing.

This is a simple string.

我想获取不包含testtesting的字符串。这是第三个字符串。

我有一个值为testtesting的数组。

唯一的解决方案,我必须遍历数组并一一搜索字符串中的数组值。

$.each(myarray , function(index, val) { 
  if (string.indexOf(val) === -1) {

  }
});

没有使用循环是否有更好的解决方案?

jquery arrays string search
1个回答
1
投票

您可以使用some()includes()功能进行操作。以下是有关some()includes()的信息。

[includes()方法区分大小写

确切地说,someincludes函数在后台(引擎盖下)循环运行。但是,您不需要编写自己的循环。

$(document).ready(function() {

  var strings = ['This is a test.', 'I am testing.', 'This is a simple string.'];
  var excludes = ['test', 'testing'];

  testFunction(strings, excludes);

  function testFunction(strings, excludes) {
    $.each(strings, function(index, string) {
      if (!excludes.some(v => string.includes(v))) {
        // here are just the strings which not includes substrings of "excludes"
      	$('#output').append(string);
      }
    })
  }

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<pre id="output"></pre>
© www.soinside.com 2019 - 2024. All rights reserved.