Javascript charAt(0)给出了意外的结果
您正在将角色与正则表达式的实例进行比较。 实际上,您希望使用正则表达式测试角色 您可以这样做:Javascript charAt(0)给出了意外的结果,javascript,Javascript,您正在将角色与正则表达式的实例进行比较。 实际上,您希望使用正则表达式测试角色 您可以这样做: var category = "a()"; if(category.charAt(0) == /^[a-zA-Z]+$/){ /*This part doesn't gets executed*/ /*What is the problem with the if condition?*/ } 进一步阅读JavaScript正则表达式: 将字符等同于正则表达式。。。不运行正
var category = "a()";
if(category.charAt(0) == /^[a-zA-Z]+$/){
/*This part doesn't gets executed*/
/*What is the problem with the if condition?*/
}
进一步阅读JavaScript正则表达式:
将字符等同于正则表达式。。。不运行正则表达式不能将==运算符与正则表达式一起使用。很可能Javascript将其视为字符串。谢谢。现在已经有了清晰的理解。由于字符串始终只有一个字符,表达式可以简化为[a-zA-Z]或/[a-Z]/i。
var category = "a()";
if (/^[a-zA-Z]+$/.test(category.charAt(0))) {
// Now it will get executed
}