如何在javascript中检查字符是字母还是数字?

时间:2020-02-19 14:29:34

标签: javascript

我是javascript新手,正在尝试检查用户输入的字母或数字。 如果用户输入“ A”,则显示字母,可以,但是如果用户输入“ 1”,我想显示 Number ,但显示字母。 我做错了。 谢谢前进

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);

2 个答案:

答案 0 :(得分:3)

这里:

if (64 < Letter.charCodeAt(0) < 91) //...

JS不是Python。您不能简单地做a < b < c,需要显式使用逻辑&&运算符:(a < b) && (b < c)

答案 1 :(得分:0)

我修改了您的条件,如以下代码所示。您也可以检出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);