Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do two identical strings not equal each other?

Tags:

javascript

Someone sent me this email:

Why do both of these alert to false?

alert('a‌' == 'a');
alert('a‌' === 'a');

Here's a demo

JSFiddle DEMO

like image 667
qwertymk Avatar asked Jan 18 '12 17:01

qwertymk


2 Answers

The first a of each is not actually a simple a. If you position the cursor right after it and hit Backspace, you delete "something", and then it returns true.

I copied your a string, this is what I get when running this code:

$a='a‌';
var_dump($a);

string(4) "a‌"

See what's wrong here? The string length is 4.

Furthermore, this:

echo base64_encode($a);

..returns:

YeKAjA==

When, for a simple string with the letter a, it should only be YQ==.

The extra character is called a "ZERO WIDTH NON-JOINER".

like image 155
cambraca Avatar answered Sep 18 '22 08:09

cambraca


Is this a trick? Did you generate those a's with some special unicode magic? I deleted the a's and re-typed them, and now both alerts show true, as they should

Updated Fiddle

like image 41
Adam Rackis Avatar answered Sep 20 '22 08:09

Adam Rackis