localeCompare helps to compare strings in a sane manner
- Published at
- Updated at
- Reading time
- 2min
Rodney Rehm recently tweeted about this function I have never heard of – String
. And wow - it can be so useful.
- Did you want to know if a string includes a given character sequence no matter if upper or lower case?
- Did you ever come across the tricky problem of sorting strings that include numeric values?
'aBcD' === 'abcd' // false
'ábcd' === 'abcd' // false
'Price 2€' > 'Price 1€' // true
'Price 20€' > 'Price 3€' // false
Using localeCompare
you can define several options that can help out here. According to MDN it returns the following value:
A negative number if the reference string occurs before the compare string; positive if the reference string occurs after the compare string; 0 if they are equivalent.
So let's have a look:
'aBcD'.localeCompare('abcd', undefined, { sensitivity: 'base' }) // 0 -> equal
'ábcd'.localeCompare('abcd', undefined, { sensitivity: 'base' }) // 0 -> equal
'Price 20€'.localeCompare('Price 3€', undefined, { numeric: true }) // 1
'Price 20€'.localeCompare('Price 3€', undefined, { numeric: false }) // -1
This can help to find out if strings have an equal base without fiddling around with numeric code points and sorting strings including numbers definitely comes in handy!
Update: as it turns out, everyone's most favorite JavaScript util (Intl
) now supports a way to compare strings, too.
const stringCollator = new Intl.Collator("en", { sensitivity: "base" });
collator.compare('aBcD', 'abcd'); // 0 -> equal
collator.compare('ábcd', 'abcd'); // 0 -> equal
It looks like Collator()
supports all of the localeCompare()
options, apparently it's faster than the original string method and the best thing: it works in all modern browsers.
![]() | ![]() | ![]() | ![]() | ![]() | ![]() | ![]() | ![]() | ![]() |
24 | 24 | 12 | 29 | 56 | 10 | 10 | 1.5 | 24 |
Hooray!
Join 5.8k readers and learn something new every week with Web Weekly.