fruitjs
fruitjs

Reputation: 765

JavaScript strict type checking fails

I was checking three Strings equality;

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

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

Upvotes: 1

Views: 312

Answers (1)

Denys Séguret
Denys Séguret

Reputation: 382160

Your question isn't totally clear to me.

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

With

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 (see note below):

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));

Note: multi-line string literals are painful. Those strings are different:

var str2 = "Hello \
    World!";
var str4 = "Hello \
World!";

Upvotes: 1

Related Questions