I need to check if two strings are in the same case. I have my own solution to this problem but I found this version and I can't understand how/why it works:
function sameCase(a, b){
if(a.toUpperCase() === a.toLowerCase() || b.toLowerCase() === b.toUpperCase()){
return -1
}else if(a === a.toLowerCase() && b === b.toLowerCase() || a === a.toUpperCase() && b === b.toUpperCase()){
return 1
}else{
return 0
}
}
Specifically this if
statement:
if(a.toUpperCase() === a.toLowerCase() || b.toLowerCase() === b.toUpperCase()){ return -1}
I know this check works against numeric characters and white space, but I don't understand why this works since it doesn't look to take these items into account.
my question: why does this function work against non-letters and numbers and even white space?
CodePudding user response:
The non-letters are not modified by toUpperCase
or toLowerCase
. Try picturing a lowercase 9
or
. That's because all those functions do is replace the individual letter characters with their uppercase or lowercase equivalents.
So, that code segment just basically checks if the string is entirely composed of non-letter characters (because 924 "
is the same in both uppercase or lowercase, however a123
is not the same in both uppercase and lowercase and thus will fail that if
statement).