Sorting Strings

Learn how to sort strings using the localeCompare method.

We'll cover the following

Often in software development, we have to sort strings. There are a few problems with string sorting:

  • Uppercase and lowercase letters are sorted differently: 'a' > 'B',
  • accented characters are completely out of sequence: 'á' > 'b'.

The localeCompare method

The localeCompare string method compares two strings in the current locale, which is based on the language settings of your browser. If the string in the localeCompare is greater than the string that invoked the localeCompare, the return value will be +ve and if the case is reverse then it will be -ve and if both the strings are equal then the return value will be 0. It helps solves both the above problems:

Get hands-on with 1200+ tech skills courses.