JavaScript === operator returning false for same strings

71 views Asked by At

I am trying to compare two strings from different sources with === operator, they are seemingly identical, but I'm getting false as a result of comparison. This is the exact code I am running:

var a = 'House is green'; // got this value from source 1
var b = 'HouseĀ isĀ green'; // got this value from source 2
console.log(a === b); // false

NOTE

You won't be able to replicate the problem by copying code from the above because HTML seems to transform every variant of white space to %20. That's why I created a simple stackblitz that replicates the problem:

https://stackblitz.com/edit/angular-s5aumq

1

There are 1 answers

0
Stefan Svrkota On BEST ANSWER

Even though these two strings seem identical, I found out the hard way that they are not. If we use encodeURI to encode both of them to their UTF-8 representation, we will get the following result:

var a = 'House is green';
var b = 'House is green';
console.log(a === b); // false

console.log(encodeURI(a)); // House%20is%20green
console.log(encodeURI(b)); // House%C2%A0is%C2%A0green

First string actually uses regular white spaces (encodes to %20) and second one uses non-breaking white spaces (encodes to %C2%A0). The best solution that I managed to figure out so far is to use replace to find all space characters and replace it with regular white space character:

var c = a.replace(/\s/g, " ");
var d = b.replace(/\s/g, " ");

console.log(c === d); // true

Here's stackblitz that reproduces the problem and provides the solution:

https://stackblitz.com/edit/angular-qmu8cg