fruitjs fruitjs - 2 years ago 105
Javascript Question

JavaScript strict type checking fails

I was checking three Strings equality;

var str1 = "Hello World!";
var str2 = "Hello \
var str3 = "Hello" + " World!";
// console.log(str2===str3);//true
console.log(str1 === str2 === str3); //false

How can we check this scenario where I want to compare 3 variables?

Answer Source

Your question isn't totally clear to me.

 Assuming your question is about how to compare the equality of 3 strings:


console.log(str1 === str2 === str3);

you're checking

(str1 === str2) === str3

(yes, the associativity is left to right here)

That is, you're comparing a boolean to a string.

What you want is

(str1 === str2) && (str2 === str3)

Assuming your question is about how to compare strings but not caring about the numbers and types of spaces (str2 in your example has more spaces):

Then the best would be to normalize your strings using a function like

function normalize(str){
    return str.replace(/\s+/g,' ');

And you can define a function comparing all your strings:

function allEquals(strs) {
   var p;
   for (var i=0; i<arguments.length; i++) {
       if (typeof arguments[i] !== "string") return false;
       var s = arguments[i].replace(/\s+/g, ' ');
       if (p !== undefined && s!==p) return false;
       p = s;
   return true;

console.log(allEquals(str1, str2, str3));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download