If this exact question has been asked before, please point me to the relevant question.
tl;dr: How does one compare two strings in JavaScript while ignoring casing according to English rules?
My code analyzes and compares data from two different sources, each with different opinions about whether keywords should be upper or lower case, meaning that a case-insensitive comparison is required. However, I don't want the system to break if used in other cultures (such as Turkey and its notorious problems with the letter I).
Does JavaScript have any way of doing a culture-independent (read: English) case-insensitive string comparison?
Comparing strings in a case insensitive manner means to compare them without taking care of the uppercase and lowercase letters. To perform this operation the most preferred method is to use either toUpperCase() or toLowerCase() function. toUpperCase() function: The str.
JavaScript is a case-sensitive language. This means that language keywords, variables, function names, and any other identifiers must always be typed with a consistent capitalization of letters.
operators differs from string comparison using the String. CompareTo and Compare(String, String) methods. They all perform a case-sensitive comparison.
localeCompare() enables case-insensitive sorting for an array.
How does one compare two strings in JavaScript without breaking if used in other cultures (such as Turkey and its notorious problems with the letter I)? Does JavaScript have any way of doing a culture-independent case-insensitive string comparison?
Yes, by simply using the standard .toLowerCase
method which is not affected by locale settings. a.toLowerCase() == b.toLowerCase()
is perfectly fine. The spec even mandates:
The result must be derived according to the case mappings in the Unicode character database
This definitely is consistent across all systems regardless of their settings.
For respecting the current locale, you would use .toLocaleLowerCase
explicitly. MDN states:
In most cases, this will produce the same result as toLowerCase(), but for some locales, such as Turkish, whose case mappings do not follow the default case mappings in Unicode, there may be a different result.
However, relying on locales does not seem to work well…
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