Skip to content

JavaScript compare strings alphabetically | Example code

  • by

Use localeCompare method compare strings alphabetically, It returns -1 since "a" < "b", 1 or 0 otherwise.

"a".localeCompare("b");

Also, if what you are sorting contains numbers, you may want:

"a5b".localeCompare("a21b", undefined, { numeric: true })

This returns -1, recognizing that 5 as a number is less than 21. Without { numeric: true } it returns 1, since “2” sorts before “5”. In many real-world applications, users expect “a5b” to come before “a21b”.

Source: stackoverflow.com

JavaScript compares strings alphabetically

Simple example code.

<!DOCTYPE html>
<html>
<body>
  <script>

   var res = "a".localeCompare("b");
   console.log(res)

 </script>
</body>
</html> 

Output:

JavaScript compare strings alphabetically

Compare 2 Strings Alphabetically for Sorting Purposes with JavaScript with the localeCompare Method. It’ll return -1 is a before b alphabetically, 0 if they’re the same, and 1 otherwise.

const arr = ['foo', 'bar', 'baz']
const sorted = arr.sort((a, b) => a.localeCompare(b))
console.log(sorted)

Output: [“bar”, “baz”, “foo”]

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

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