Reputation: 213
I am new to javascript I'm trying to check user entered the alphabet or a number. if the user enters "A" it shows Alphabet it's ok but if the user enters "1" I want to show Number but its show alphabet. where i done wrong. Thanks Advance
function CHECKCHARATCTER(Letter) {
if (Letter.length <= 1) {
if ((64 < Letter.charCodeAt(0) < 91) || (96 < Letter.charCodeAt(0) < 123)) {
return "Alphabhate";
}
else if (47 < Letter.charCodeAt(0) < 58) {
return "NUMBER";
}
else { return "Its NOt a NUMBER or Alphabets"; }
}
else { return ("Please enter the single character"); }
}
a = prompt("enter the number or Alphabhate");
alert(typeof (a));
b = CHECKCHARATCTER(a);
alert(b);
Upvotes: 0
Views: 5974
Reputation: 59
You can use regular expressions. Please have a look at regular expressions. It will be very helpful.
function checkAlphaNum(char) {
let alphaReg = new RegExp(/^[a-z]/i);
let numReg = new RegExp(/^[0-9]/);
if(alphaReg.test(char)) {
return "ALPHABET";
} else if(numReg.test(char)) {
return "NUMBER";
} else {
return "OTHER";
}
}
console.log("Output : ", checkAlphaNum('A'));
console.log("Output : ", checkAlphaNum(1));
Upvotes: 1
Reputation: 641
I modified you conditions as it's shown in the following code. Also you can check it out here
function CHECKCHARATCTER(Letter){
if (Letter.length <= 1)
{
if (Letter.toUpperCase() != Letter.toLowerCase()) {
return "Alphabet";
}
else if (!isNaN( Letter)) {
return "Number";
} else{
return "Its Not a Number or Alphabet";
}
}
else {
return("Please enter the single character");
}
}
input = prompt("enter the Number or Alphabet");
output = CHECKCHARATCTER(input);
alert(output);
Upvotes: 0
Reputation: 14669
Here:
if (64 < Letter.charCodeAt(0) < 91) //...
JS isn't Python. You can't simply do a < b < c
, you need to explicitly use the logical && operator: (a < b) && (b < c)
.
Upvotes: 3