Skip to content Skip to sidebar Skip to footer

JavaScript: Culture-independent Case-insensitive String Comparison

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 Eng

Solution 1:

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


Solution 2:

In theory there is a method for that: String.localCompare().

The problem is that it's not implemented correctly by most browsers.

You might have more luck using String.toLocaleLowerCase().

Example:

if ("Äpfel".toLocaleLowerCase() == "äpfel".toLocaleLowerCase()) alert("Case Insensitive Match")

Be aware that following will not match (because ä and a are different characters):

if ("Äpfel".toLocaleLowerCase() == "apfel".toLocaleLowerCase()) alert("Case Insensitive Match")

Solution 3:

You can use localeCompare but be aware that it is implemented differently between browsers. What seems to work in Chrome/Firefox/IE11 is:

first.localeCompare("First", navigator.language, { sensitivity: "base" }) === 0

var console = function() {
    var log = function(message) {
      strMessage = "<p>" + message + "</p>";
      $("#console").append(strMessage);
    };
    
    return {
        log: log
    };
}()

var first = "first";
var result = first.localeCompare("First", navigator.language, { sensitivity: "base" }) === 0;
console.log(result);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="console">
</div>

Post a Comment for "JavaScript: Culture-independent Case-insensitive String Comparison"