Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Intl.Collator is a web UI superpower but apparently a well-kept secret: it gives you string sorting that takes into account local conventions for things like accented characters and even sorts strings containing numerical parts into natural rather than lexicographical order (that is, it correctly sorts “Item 1” before “Item 2” before “Item 10”).


The same options [1] are built into `String.prototype.localeCompare` (which is just a handy shortcut for calling `Collator` [2]). So for example:

``` ['B 1', 'A 20', 'A 3'].sort((a, b) => a.localeCompare(b, 'en', { numeric: true })) // ['A 3', 'A 20', 'B 1'] ```

[1] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...

[2] https://tc39.es/ecma402/#sup-String.prototype.localeCompare


Intl.DateTimeFormat is also really nicely done, because it limits the developer to "skeletons": you say what fields you want / need, and the browser will render what it has with at least those. Meaning the OS / user can override your whims if that's better or more readable. There's also formatRange which can provide localised range notations.

Although later on formatToParts was added which allows the developer to ignore the settings and really only use the bits they wanted anyway.


Oh wow - lexicographical sorting built in to the browser!


This alone is worthy of its own post!




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: