I would like to compare two variables to see if they are the same, but I want this comparison to be case-insensitive.
For example, this would be case sensitive:
if($var1 == $var2){ ... }
But I want this to be case insensitive, how would I approach this?
The equalsIgnoreCase() method compares two strings, ignoring lower case and upper case differences. This method returns true if the strings are equal, and false if not. Tip: Use the compareToIgnoreCase() method to compare two strings lexicographically, ignoring case differences.
JavaScript is a case-sensitive language. This means that the language keywords, variables, function names, and any other identifiers must always be typed with a consistent capitalization of letters.
A string comparison is case sensitive when you don't want it to be, or vice versa.
Java String equalsIgnoreCase() method is used to compare a string with the method argument object, ignoring case considerations. In equalsIgnoreCase() method, two strings are considered equal if they are of the same length and corresponding characters in the two strings are equal ignoring case.
This is fairly simple; you just need to call strtolower()
on both variables.
If you need to deal with Unicode or international character sets, you can use mb_strtolower()
.
Please note that other answers suggest using strcasecmp()
—that function does not handle multibyte characters, so results for any UTF-8 string will be bogus.
strcasecmp()
returns 0 if the strings are the same (apart from case variations) so you can use:
if (strcasecmp($var1, $var2) == 0) { }
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