JavaScript字符串匹配和长度

时间:2016-03-02 21:50:46

标签: javascript match string-length

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

到目前为止,这是它的代码:

var username = "A1KJ!PNSG2Q0";

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

感谢先进为任何人提供帮助!

1 个答案:

答案 0 :(得分:0)

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

&#13;
&#13;
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' )
}
&#13;
&#13;
&#13;