I ran into a pretty strange issue with my latest JS project. I usually compare strings using ===
but when comparing the string properties of two of different objects I got false even though they were the exact same strings. I tested this in my Node.js interpreter by doing the following:
> x = {str: 'hello'}
{ str: 'hello' }
> y = {str: 'hello'}
{ str: 'hello' }
> y.str === x.str
true
So I couldnt figure out why my code wasnt working. But when I switch from using ===
to str1.localeCompare
BOOM, it works. Whats the difference between the two?
===
looks for exactly the same bytes in the strings.
.localeCompare()
allows for the fact that you may want to ignore certain differences in the strings (such as puncutation or diacriticals or case) and still allow them to compare the same or you want to ignore certain differences when deciding which string is before the other. And, it provides lots of options to control what comparison features are or are not used.
If you read the MDN documentation for string.prototype.localeCompare()
, you can see a whole bunch of options you can pass in to control how the compare works. On a plain ascii string with no special characters in it that are all the same case, you are unlikely to see a difference, but start getting into diacriticals or case issues and localCompare()
has both more features and more options to control the comparison.
Some of the options available for controlling the comparison:
In addition, localeCompare()
returns a value (negative, 0 or positive) that is perfectly aligned to use with a .sort()
callback.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With