如何判断字符串中的所有字符是否相同

时间:2011-07-08 02:55:42

标签: jquery

我想知道字符串中的所有字符是否相同。我用它来输入密码 所以我告诉用户你的密码非常明显。 我创建了这个

$(function(){
    $('#text_box').keypress(function(){
        var pass = $("#text_box").val();
        if(pass.length<7)
            $("#text_box_span").html('password must be atleast 6 characters');
        else
            $("#text_box_span").html('Good Password');
    });
});

如何实现相同的角色?

4 个答案:

答案 0 :(得分:23)

/^(.)\1+$/.test(pw) // true when "aaaa", false when "aaab".

使用正则表达式捕获第一个字符,然后反向引用它(\1),检查它是否已重复。

Here is the fiddle Brad Christie posted in the comments

答案 1 :(得分:1)

我用纯javascript写道:

 var pass = "112345"; 
    var obvious = false; 

    if(pass.length < 7) { 
       alert("password must be atleast 6 characters");
    } else { 

    for(tmp = pass.split(''),x = 0,len = tmp.length; x < len; x++) {
        if(tmp[x] == tmp[x + 1]) {
           obvious = true; 
        }
    }

    if(obvious) { 
       alert("your password is very obvious.");
    } else { 
      alert("Good Password");
    }
    }

答案 2 :(得分:1)

这也有效: http://jsfiddle.net/mazzzzz/SVet6/

function SingleCharacterString (str)
{
    var Fletter = str.substr(0, 1);
    return (str.replace(new RegExp(Fletter, 'g'), "").length == 0); //Remove all letters that are the first letters, if they are all the same, no letters will remain
}

在您的代码中:

$(function(){
    $('#text_box').keypress(function(){
        var pass = $("#text_box").val();
        if(pass.length<7)
            $("#text_box_span").html('password must be atleast 6 characters');
        else if (SingleCharacterString(pass))
            $("#text_box_span").html('Very Obvious.');
        else
            $("#text_box_span").html('Good Password');
    });
});

答案 3 :(得分:0)

这个允许您指定要检查的特定字符。例如,所有字符都是字母&#39; Z&#39;?

function same(str,char){
    var i = str.length;
    while (i--) {
        if (str[i]!==char){
            return false;
        }
    }
    return true;
}
// same('zzza','z'); returns false