【问题标题】:Check if string contains an element from array ignoring case (JavaScript)检查字符串是否包含数组中忽略大小写的元素(JavaScript)
【发布时间】:2020-11-05 03:37:27
【问题描述】:

我有这段代码来获取我需要检查的字符串

var f = document.getElementsByClassName('first');
var c = f[0];
var xx = c.getElementsByTagName('a')[0];
var chk = xx.innerText;

还有一个数组

const ar = ["[Text]", "[More]", "[AnotherText]", "[Stuff]", "[Yes]"]

有问题的字符串 (chk) 可以包含该数组中的任何值,并且可以是任何大小写

示例:[TExT] some random text afterwards

我需要检查chk 是否包含来自ar 的任何值,忽略大小写

试过

if (ar.some(chk => chk.toLowerCase().includes(chk))){console.log("yay")}

if (ar.some(chk.includes.bind(chk)))

但它们返回未定义

【问题讨论】:

  • chk => chk.toLowerCase().includes(chk) 更改您的变量名称。
  • 回调参数和搜索字符串不要使用同一个变量chk

标签: javascript html arrays string


【解决方案1】:

改变

chk => chk.toLowerCase().includes(chk)

val => val.toLowerCase().includes(chk.toLowerCase())

const ar = ["[Text]", "[More]", "[AnotherText]", "[Stuff]", "[Yes]"];

const isContain = (arr, chk) =>
  arr.some(
    (val) =>
      val.toLowerCase().includes(chk.toLowerCase()) ||
      chk.toLowerCase().includes(val.toLowerCase())
  );
  
  
console.log(isContain(ar, "tExt"))

【讨论】:

  • 回调参数也需要使用不同的变量。
猜你喜欢
  • 2015-07-18
  • 2011-01-17
  • 2016-09-22
  • 2012-12-10
  • 2020-06-13
  • 2019-10-22
  • 1970-01-01
  • 2016-11-11
  • 2013-05-12
相关资源
最近更新 更多