Javascript String localeCompare()

The JavaScript String localeCompare() method checks if a given string comes before, after, or is same as other string in sort order.

The syntax of the localeCompare() method is:

str.localeCompare(compareStr, locales, options)

Here, str is a string.

localeCompare() Parameters

The localeCompare() method takes in:

  • compareStr - The string against which str is compared.
  • locales and options (optional) - These arguments customize function by specifying what formatting conventions to use.

Return value from localeCompare()

  • Returns negative number (-1) if the reference string is sorted before compareStr.
  • Returns 0 if two strings are equivalent.
  • Returns positive number (1) if the reference string is sorted after compareStr.

Note: Since returned negative and positive integers vary between browsers, do not rely on exact values -1 or 1.

Example 1: Using localeCompare()

// letter 'h' comes after 'c'
let result = "h".localeCompare("c");
console.log(result); // 1

// letter 'a' comes before 'c', so 'after' comes before 'car'
let result1 = "after".localeCompare("car");

// words 'JavaScript' & 'JavaScript' are equivalent
let result2 = "JavaScript".localeCompare("JavaScript");
console.log(result2); // 0



Example 2: Using localeCompare() with locales and options

// using locale
let value1 = "ä".localeCompare("z", "de");
console.log(value1); // a negative value: in German, ä sorts before z

let value2 = "ä".localeCompare("z", "sv");
console.log(value2); // a positive value: in Swedish, ä sorts after z

// default
console.log("5".localeCompare("40")); // 1

// using options
let value3 = "5".localeCompare("40", undefined, { numeric: true });
console.log(value3); // a negative value

let value4 = "Cliché".localeCompare("café", "fr", { ignorePunctuation: true });
console.log(value4); // a positive value