Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 536
LegendDemonSlayer Avatar asked Jan 08 '18 06:01

LegendDemonSlayer


People also ask

Is includes in JavaScript case insensitive?

Case Insensitive SearchBoth String#includes() and String#indexOf() are case sensitive. Neither function supports regular expressions.

How do you make a case insensitive in JavaScript?

The best way to do a case insensitive comparison in JavaScript is to use RegExp match() method with the i flag.

How do you make a function case insensitive?

A function is not "case sensitive". Rather, your code is case sensitive. The way to avoid this problem is to normalize the input to a single case before checking the results. One way of doing so is to turn the string into all lowercase before checking.


1 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 );  
like image 86
gurvinder372 Avatar answered Oct 08 '22 18:10

gurvinder372