JavaScript strict type checking fails -
i checking 3 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 check scenario want compare 3 variables?
your question isn't totally clear me.
assuming question how compare equality of 3 strings:
with
console.log(str1 === str2 === str3);
you're checking
(str1 === str2) === str3
(yes, associativity left right here)
that is, you're comparing boolean string.
what want is
(str1 === str2) && (str2 === str3)
assuming question how compare strings not caring numbers , types of spaces (see note below):
then best normalize strings using function like
function normalize(str){ return str.replace(/\s+/g,' '); }
and can define function comparing strings:
function allequals(strs) { var p; (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 painful. strings different:
var str2 = "hello \ world!"; var str4 = "hello \ world!";
Comments
Post a Comment