JavaScript 字符串匹配和长度

JavaScript String Match and Length

所以,我需要你在我的代码中匹配从 A 到 z 的所有字符,然后得到它的长度。基本上我需要在字符串值中使用一个匹配项,然后获取该匹配项的长度。现在它根本不起作用。如果我删除长度,我得到一个空值。

目前的代码如下:

var username = "A1KJ!PNSG2Q0";

if(username.match(/^[A-z]+$/g).length < 5) {
    alert("Yay!")
}

在此先感谢大家的帮助!

正确的正则表达式是 /[A-z]{1}/g。您想要计算匹配 [A-z] 的每个字符出现的次数。如果没有 {0},它只会计算字符块,例如 PNSG 将算作一个。

var username = "A1KJ!PNSG2Q0";

document.write('Matches: '+username.match(/[A-z]{1}/g)+'<br>')
if(username.match(/[A-z]{1}/g).length < 5) {
    document.write('Yeah' )
}
else
{
document.write('Computer says No'+'<br>' )
}


var username = "A1KJ!7543210";

document.write('Matches: ' + username.match(/[A-z]{1}/g)+'<br>')
if(username.match(/[A-z]{1}/g).length < 5) {
    document.write('Yeah' )
}