Compare if az or AZ and output the result using java-script function
I am learning JavaScript. Very new and knowledgable basic. I am playing around with various JavaScript variants.
I am comparing az (lower case) and AZ (upper case) from user input. and providing a base of responses at the entrance.
I can usually do it with this long code:
<script>
var x=prompt("Enter Your character");
switch(x){
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'g':
case 'h':
case 'i':
case 'j':
case 'k':
case 'l':
case 'm':
case 'n':
case 'o':
case 'p':
case 'q':
case 'r':
case 's':
case 't':
case 'u':
case 'v':
case 'w':
case 'x':
case 'y':
case 'z':
document.write("Lower case");
break;
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
case 'G':
case 'H':
case 'I':
case 'J':
case 'K':
case 'L':
case 'M':
case 'N':
case 'O':
case 'P':
case 'Q':
case 'R':
case 'T':
case 'U':
case 'V':
case 'W':
case 'X':
case 'Y':
case 'Z':
document.write("Upper case");
break;
default:
document.write("It is number");
break;
}
With a switch, I want to achieve the same output, but with less code! Something like that:
var x=prompt("Enter Your character");
switch(x){
case x>='a'||x<='z':
document.write("Lower case");
break;
case x>='A'||x<='Z':
document.write("Upper case");
break;
default:
document.write("It is number");
break;
Any help?
Please, I want to do this with just the switch function. I know I can do it with an if / else function, but I want to do it with a switch. If this is not possible with a switch, let me know :-)
source to share
The operator switch
compares the input expression with each case argument using strict comparison.
So, use true
inside a switch clause and specify the expressions that are evaluated in the true
case:
var x = prompt("Enter Your character");
switch (true) {
case x >= "a" && x <= "z":
alert("Lower case");
break;
case x >= "A" && x <= "Z":
alert("Upper case");
break;
default:
alert("Something else");
break;
}
I personally don't recommend this. This is for teaching only.
source to share
You can try something like this.
<script>
var x=prompt("Enter Your character");
if (x.test(/[a-z]/)) {
document.write("Lower case");
} else if (x.test(/[A-Z]/)) {
document.write("Upper case");
} else {
document.write("It is number");
}
</script>
You can see more information here: https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test
source to share
The parameter to the operator case
is something that an equality comparison is done for, you don't put a comparison. If you want to make a comparison, use if
rather than switch
. Also, you should combine comparisons with &&
, not||
if (x >= 'a' && x <= 'z') {
document.write('Lower case');
} else if (x >= 'A' && x <= 'Z') {
document.write('Upper case');
} else if (x >= '0' && x <= '9') {
documennt.write('Number');
} else {
document.write('Something else');
}
source to share