How to compare Unicode strings in Javascript?

后端 未结 6 2040
不知归路
不知归路 2020-11-29 21:34

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

6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-29 22:12

    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.

提交回复
热议问题