qwerty
qwerty

Reputation: 93

Check if string contains an element from array ignoring case (JavaScript)

I have this code to get the string I need to check against

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

And an array

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

The string (chk) in question can contain any of the values from that array, and can be any case

Example: [TExT] some random text afterwards

What I need is to check if chk contains any of the values from ar, ignoring the case

Tried

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

or

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

but they return undefined

Upvotes: 0

Views: 147

Answers (1)

Siva Kondapi Venkata
Siva Kondapi Venkata

Reputation: 11001

Change from

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

to

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

or

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

Upvotes: 3

Related Questions