I recently had to do work on localeCompare in JavaScript and though I would write a plugin in JQuery and share it.

Javascript Locale Compare

JavaScript provides a localeCompare function for comparing two strings in the current locale. The locale is based on the language settings of the browser. To explain locale compare lets look at some text.

Basically the function returns

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

Problem at hand

When we are localizing applications we tend to use some kind of resources key, in .NET we use resx files to localize an application. For example we may have 3 key, something like the image below
resx

In your code you may say something like

The output would display Apple, Orange and Pear and for English, the list is sorted properly, but if you translate those keys into french the sorting is incorrect, since in french Apple is Pomme. The display in French would be Pomme, Orange, Poire, which is incorrect. The sorting would also work for chinese 橙, 苹果, 梨.

In order to fix this I created a jquery plugin that would allow me to sort all unordered list

Below is the code for jquery plugin, I also have it on jsfiddle http://jsfiddle.net/taswar/bR9fZ/. One can also provide their own algorithm for compare, since if you are sorting a large amount of text, localeCompare may not be the most efficient algorithm and some browsers may implement it differently.