Fawad Ghafoor
Fawad Ghafoor

Reputation: 6207

How to tell if all characters in a string are same

I want to know if all characters in a string are same. I am using it for a Password so that i tell the user that your password is very obvious. I have crated this

$(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');
    });
});

How can I achieve the same characters?

Upvotes: 8

Views: 8489

Answers (5)

user11006286
user11006286

Reputation:

Simple one-liner:

str.split('').every((char) => char === str[0]);

Upvotes: 1

Ronnie Smith
Ronnie Smith

Reputation: 18555

This one allows you to also specify a particular character to check for. For example, are all characters the letter 'Z'?

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

Upvotes: 0

Brad Christie
Brad Christie

Reputation: 101594

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

Captures the first character using regex, then backreferences it (\1) checking if it's been repeated.

Here is the fiddle that Brad Christie posted in the comments

Upvotes: 30

Jess
Jess

Reputation: 8700

This would also work: 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
}

In your code:

$(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');
    });
});

Upvotes: 2

The Mask
The Mask

Reputation: 17427

I wrote in pure 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");
    }
    }

Upvotes: 1

Related Questions