我正在尝试编写代码来检查有效的用户名。我做错了什么?如果我输入我的用户名并以a-z开头,则说它无效。 另外,我不能使用正则表达式。
var BR = "<br />";
var username = "";
var letter1;
var digit;
letter1 = username.substr(0,1);
username = prompt("Please enter a your username:");
//First letter begin with a letter
if (letter1 >= "a" && letter1 <= "z") {
document.write("The first character is valid." + BR);
}
else {
document.write("The first character is not valid." + BR);
}
感谢您的帮助!
答案 0 :(得分:0)
检查此小提琴http://jsfiddle.net/Dilip/2t9n6vpt/1/
var BR = "<br />";
var username = "";
var letter1;
var digit;
letter1 = username.substr(0,1);
username = prompt("Please enter a your username:");
//First letter begin with a letter
var aCode = 'a'.charCodeAt(0);
var zCode = 'z'.charCodeAt(0);
if (username.charCodeAt(0) >= aCode && username.charCodeAt(0) <= zCode) {
document.write("The first character is valid." + BR);
}
else {
document.write("The first character is not valid." + BR);
}
username.charCodeAt(0)
将给出第一个字符的ASCII值。你可以用这个来检查。
答案 1 :(得分:0)
把letter1 = username.substr(1,2)声明 AFTER 你从行读取用户名 username = prompt(“请输入您的用户名:”);
在提示符弹出用户名后,您应该获得用户名的第一个字母。
答案 2 :(得分:0)
切换“letter1 =”和“username =”语句的顺序。
答案 3 :(得分:0)
将您的信件转换为ascii,然后按以下方式检查:https://jsfiddle.net/pyexm7us/2/
我也检查过大写字母:
的Javascript
var BR = "<br />";
var username = "";
var digit;
username = prompt("Please enter a your username:");
var ascii = username.charCodeAt(0);
//First letter begin with a letter
if (ascii >= 97 && ascii <= 122 || ascii >= 65 && ascii <= 90) {
document.write("The first character is valid." + BR);
}
else {
document.write("The first character is not valid." + BR);
}