Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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")

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>

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top