javascriptcomparepolish

How to compare Unicode strings in Javascript?


When I wrote in JavaScript "Ł" > "Z" it returns true. In Unicode order it should be of course false. How to fix this? My site is using UTF-8.


Solution

  • You can use Intl.Collator or String.prototype.localeCompare, introduced by ECMAScript Internationalization API:

    "Ł".localeCompare("Z", "pl");              // -1
    new Intl.Collator("pl").compare("Ł","Z");  // -1
    

    -1 means that Ł comes before Z, like you want.

    Note it only works on latest browsers, though.