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
?
Case Insensitive SearchBoth String#includes() and String#indexOf() are case sensitive. Neither function supports regular expressions.
The best way to do a case insensitive comparison in JavaScript is to use RegExp match() method with the i flag.
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.
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 );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With