【问题标题】:How to check if one of the array value exist in a string?如何检查字符串中是否存在数组值之一?
【发布时间】:2020-08-23 15:14:38
【问题描述】:

我有三种类型的字符串。

This is a test.

I am testing.

This is a simple string.

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

我有一个包含值 testtesting 的数组。

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

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

  }
});

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

【问题讨论】:

  • myarray 包含两个值 testtesting
  • string 是问题中提到的三个字符串之一。
  • 所以,您的主要问题是如何检查myarray 字符串是否存在于单个string 中或没有循环?
  • 我的问题是如何在没有循环的情况下检查 myarray 字符串是否存在于单个字符串中
  • 我认为你可以简单地做if (string.indexOf(myarray[0]) === -1 && string.indexOf(myarray[1]) === -1) { .... } 然后不需要循环。

标签: jquery arrays string search


【解决方案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>

【讨论】:

  • 我想说“不写循环”有点误导 :D 在幕后 .some.includes 实际上也遍历给定的数组。但是答案仍然是正确的:)
  • @PhilippMeissner 谢谢,我已将您的想法添加到我的回答中。
猜你喜欢
  • 1970-01-01
  • 2022-12-18
  • 2016-06-07
  • 2012-05-09
  • 1970-01-01
  • 2021-12-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多