Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing strings with localeCompare vs ===?

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?

like image 560
Daniel Kobe Avatar asked Nov 03 '15 00:11

Daniel Kobe


1 Answers

=== 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:

  1. numeric collation
  2. diacritical sensitivity
  3. ability to ignore punctuation
  4. case first
  5. control whether upper or lower case compares first

In addition, localeCompare() returns a value (negative, 0 or positive) that is perfectly aligned to use with a .sort() callback.

like image 199
jfriend00 Avatar answered Sep 24 '22 00:09

jfriend00