Skip to content

JavaScript localeCompare | String method

  • by

JavaScript localeCompare() method is used to compare two strings in the current locale. This method returns a number indicating whether a reference string comes before or after or is the same as the given string in sorted order.

string.localeCompare(compareString)

This method returns sort order -1, 1, or 0 (for before, after, or equal) and the current locale is based on the language settings of the browser.

Return Value

  • -1 if the string is sorted before the compareString
  •  0 if the two strings are equal
  •  1 if the string is sorted after the compareString

JavaScript localeCompare

Simple example code.

<!DOCTYPE html>
<html lang="en">
<body>
  <script>
    let text1 = "ab";
    let text2 = "cd";
    let text3 = "ab"

    let res1 = text1.localeCompare(text2);
    let res2 = text2.localeCompare(text1);
    let res3 = text1.localeCompare(text3);

    console.log(res1)
    console.log(res2)
    console.log(res3)
  </script>
</body>
</html>

Output:

JavaScript localeCompare String method

More example

const a = 'réservé'; // with accents, lowercase
const b = 'RESERVE'; // no accents, uppercase

console.log(a.localeCompare(b)); // 1
console.log(a.localeCompare(b, 'en', { sensitivity: 'base' })); // 0

Do comment if you have any doubts or suggestions on this JS string method.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading