Reputation: 765
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
Reputation: 382160
Your question isn't totally clear to me.
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)
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