How to use localeCompare() in JavaScript?

The localeCompare() method is a built-in JavaScript function that compares two strings in a case-sensitive or case-insensitive manner, based on the current locale. It returns a number indicating whether the string it is called on comes before, after, or is equal to the string passed as an argument.

localeCompare(string2, locale, options) Syntax

The localeCompare(string2, locale, options) method returns:

  • negative number if string1 comes before string2 in the sort order
  • 0 if string1 and string2 are equal
  • a positive number if string1 comes after string2 in the sort order

You can pass an options object as the third parameter to the localeCompare() method:
string1.localeCompare(string2, undefined, { sensitivity: 'base' });
to specify the sensitivity of the comparison, either 'accent', 'case' or 'base'.
The undefined value passed as the second parameter to the localeCompare() method is used to indicate that the method should use the default locale of the system so that the comparison is done according to the conventions of the user’s current locale. For example, you can use “en-US” to compare strings using the US English locale, or “fr-FR” to compare strings using the French locale.
string1.localeCompare(string2, "en-US", { sensitivity: 'base' });

localeCompare() Case Insensitive Comparison

let string1 = "";
let string2 = "YARKUL.COM";
if (string1.localeCompare(string2, undefined, { sensitivity: 'base' }) === 0) {
  console.log("The strings are equal, ignoring case.");
} else {
  console.log("The strings are not equal.");

localeCompare Example JavaScript

As the above example shows, if the localeCompare() method returns 0, that means the two strings are equal, ignoring case. Keep in mind that localeCompare() will take into account the current system’s locale and it’s not recommended to use this method to compare strings with different languages or scripts. Read my article about case insensitive comparing using toUpperCase and toLowerCase methods.

Leave a Comment