qwertymk
qwertymk

Reputation: 35256

How do two (seemingly!) identical strings not equal each other?

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

Upvotes: 12

Views: 16906

Answers (3)

cambraca
cambraca

Reputation: 27839

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".

Upvotes: 17

Li0liQ
Li0liQ

Reputation: 11254

For the first 'a' console says:

'a‌'.charCodeAt(0)
97
'a‌'.charCodeAt(1)
8204

8204 seems to be a unicode value for Zero-width non-joiner

Whilst for the second its:

'a'.charCodeAt(0)
97
'a'.charCodeAt(1)
NaN

It's natural that different strings are different :).

Upvotes: 6

Adam Rackis
Adam Rackis

Reputation: 83358

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

Upvotes: 16

Related Questions