charAt(0)给出了意外的结果

Javascript .charAt(0) gives unexpected results

本文关键字:意外 结果 charAt      更新时间:2023-09-26
var category = "a()";
if(category.charAt(0) == /^[a-zA-Z]+$/){

    /*This part doesn't gets executed*/
    /*What is the problem with the if condition?*/

}

您正在将您的字符与正则表达式的实例进行比较。实际上,您想要用正则表达式测试您的角色。

你可以这样做:

var category = "a()";
if (/^[a-zA-Z]+$/.test(category.charAt(0))) {
    // Now it will get executed
}

关于JavaScript正则表达式风格的进一步阅读:
http://www.regular-expressions.info/javascript.html