LocV's Nest
LocV's Nest

Reputation: 118

Is it posible to two equal strings be unequal in Javascript?

Me and my team are doing a React/Redux project and now I want to filter out duplicated tags, but I realize someone has put some tricky strings to the tags data like this

And when I log those tags to the console, for example the first and the second tag of the tag list are looking like the same is "HumanIty" but when I compare them with even strict equal operator, I've got the false result.

When I try to select and copy the text content in both string tags, then paste them back to the console, I got a surprise result - The string in the second tag somehow has spaces between characters (red dots in the picture below)

Someone has to face this problem before please give me some explain about this. Thank you.

Upvotes: 1

Views: 365

Answers (3)

LocV's Nest
LocV's Nest

Reputation: 118

I've found out that one of those two look-alike strings contains some special invisible, zero-width character called Byte Order Mark (https://www.ionos.com/digitalguide/websites/web-development/byte-order-mark/)

and we could strip out those characters by the regex /[^\x20-\x7E]/g as (https://www.w3resource.com/javascript-exercises/javascript-string-exercise-32.php)

We could detect the existence of the invisible character with some tools which show unicode character (https://qaz.wtf/u/show.cgi?show=a%E2%80%8Bc&type=string)

Upvotes: 0

Marco
Marco

Reputation: 7261

To answer your question directly:

Is it possible for to two equal strings be unequal in Javascript?

No.

As mentioned in the comments you have some invisible characters in your strings, making them unequal when you compare them.

To fix the problem, remove the invisible characters with a method of your choice (my recommendation would be to not let user input invisible characters in the first place).

Upvotes: 2

WBT
WBT

Reputation: 2465

What is the .length property of each string?

If you iterate an index variable over each character position from 0 (inclusive) to length (exclusive), and print the .charCodeAt(index), what do you see?

In doing this, you might see differences between the strings.

Upvotes: 1

Related Questions