Javascript Includes() Case Insensitive

Javascript Includes() Case Insensitive

I have an array of strings that I need to loop and check against with another passed in string.

var filterstrings = ['firststring','secondstring','thridstring'];
var passedinstring = localStorage.getItem("passedinstring");

for (i = 0; i < filterstrings.lines.length; i++) {
    if (passedinstring.includes(filterstrings[i])) {
        alert("string detected");
    }
}

How do I ensure that case sensitivity is ignored here (preferably by using regex) when filtering, if the var passedinstring were to have strings like FirsTsTriNg or fiRSTStrING?

2

10 Answers

You can create a RegExp from filterstrings first

var filterstrings = ['firststring','secondstring','thridstring'];
var regex = new RegExp( filterstrings.join( "|" ), "i");

then test if the passedinstring is there

var isAvailable = regex.test( passedinstring ); 
5

You can simply convert the passedinstring to lowercase.

var passedinstring = localStorage.getItem("passedinstring").toLowerCase();
2

ES6 array method filter() can simplify the solution to a single line. Use includes() method to determine whether an array includes a certain value among its entries in conjunction to the toLowerCase() method to convert it to lowercase.

var filterstrings = ['firststring','secondstring','thridstring'];
var passedinstring = localStorage.getItem("passedinstring");

// convert each string from filterstrings and passedinstring to lowercase
// to avoid case sensitive issue.
filteredStrings = filterstrings.filter((str) => str.toLowerCase().includes(passedinstring.toLowerCase())
4

convert filterstring and passedinstring to lowercase and compare

var filterstrings = ['firststring','secondstring','thridstring'];
var passedinstring = 
localStorage.getItem("passedinstring").toLowerCase();

for (i = 0; i < filterstrings.lines.length; i++) {
   if (passedinstring.includes(filterstrings[i].toLowerCase())) {
       alert("string detected");
   }
}

You can switch .includes with the .some method which returns a boolean.
It will exit as soon as a match was found, which is great for performance for huge arrays:

.some(item => item.toLowerCase() == lookup.toLowerCase())

Demo:

var arr = ['foo','bar','bar'];
var lookup = "bAr";

// case-sensetive
console.log( arr.includes(lookup) )

// case-insensetive without caring about the type
console.log( arr.some(x => x.toLowerCase() == lookup.toLowerCase()) ) 

Or define your own Array prototype method with a unique name:

// the name ("_includes") should be unique enough not to ever be overriten 
// by future language updates or 3rd-party scripts
Array.prototype._includes = function(target){ 
  return this.some(x => x.toLowerCase() == (target||'').toLowerCase()) 
}

console.log( 
  ['foo', 'bar', 'bar']._includes("bAr") 
)
3

Fixed case sensitivity issue using toLowerCase(). It turns all the string to lower case while comparing.

var product=productList.filter((x) => x.Name.toLowerCase().includes(("Active").toLowerCase()))

My option is comparing UPPER with UPPER or lower with lower transforming both sides (i did it often in SQL):

    var filterstrings = ['firststring','secondstring','thirDstrIng'];
    var passedinstring =  'ThIrDsTrInG3';
    
    //used for of just to make it more readable
    for (filterstring of filterstrings) {
        if (passedinstring.toUpperCase().includes(filterstring.toUpperCase())) {
            alert("string detected");
        }
    
    }

Prompts string detected

var filterstrings = ['firststring','secondstring','thridstring'];
var passedinstring = localStorage.getItem("passedinstring");

filterstrings.filter(item => item.name.toLowerCase().includes(passedinstring.toLowerCase()))
1

I believe this would be simpler, shorter and more understandable.

  const q = new RegExp(query, 'i');

  filteredUsers = users.filter((user: User) => {
    return (
      user.entity.short.match(q) ||
      user.firstname.match(q) ||
      user.lastname.match(q)
    );
  });
1

You can try this.

var fruits = ["Banana", "Orange", "Apple", "Mango"];
string = fruits.join(' ').toUpperCase();
// Output"BANANA ORANGE APPLE MANGO"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Marcus Vance
Author

Marcus Vance

Marcus Vance is a cybersecurity auditor and technology writer dedicated to educating the public about online safety, data privacy regulations, enterprise security, and emerging cyber threats.