[edit] Let's add this disclaimer: this use of switch
is considered EVIL or ABUSIVE. Some Disciples Of The Javascript also consider the use of ternaries as a major SIN. So beware of using them, because hell may await you, so the Gospel goes.
You can use switch
like this 1:
switch (true) {
case (parseInt(charCode) >= 65 && parseInt(charCode) <=90): //UPPERCASE
alert("UP");
break;
case (parseInt(charCode) >= 97 && parseInt(charCode) <=122): //LOWERCASE
alert("LO");
break;
case (parseInt(charCode) >= 48 && parseInt(charCode) <=57): //NNUMBERS
alert("NUM");
break;
default: break
}
it's pretty bulky. You don't have to use parseInt
if you derive charCode
came from event.keyCode
. If you need to use parseInt
, don't forget to provide the radix, or better still, use Number
to convert to a number.
Anyway using a ternary is an alternative for this:
alert( charCode >= 65 && charCode <= 90
? 'UP'
: charCode >= 97 && charCode <= 122
? 'LO'
: charCode >= 48 && charCode <= 57
? 'NUM'
: 'OTHER'
);
[edit] Let's see if the following alternative can satisfy the church of Javascript Coders...
Another alternative is using a RegExp
with the character derived from the keyCode
:
var chr = String.fromCharCode(charCode),
alertval = /[a-z]/.test(chr) ? 'LO'
: /[A-Z]/.test(chr) ? 'UP'
: /[0-9]/.test(chr) ? 'NUM'
: 'OTHER';
alert(alertval);
As a last alternative (man, javascript is so versatile!) I present:
var check = String.fromCharCode(charCode)
.replace(/([a-z])|([A-Z])|([0-9])|(.+)/,
function(a,b,c,d) {
return b ? 'LO' : c ? 'UP' : d ? 'NUM' : 'OTH';
});
1 some notes on that 'trick'