Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if a string contains a sequence of repeated letters

Using JavaScript, I need to check if a given string contains a sequence of repeated letters, like this:

"aaaaa"

How can I do that?

like image 903
vetri02 Avatar asked May 30 '11 13:05

vetri02


5 Answers

This will check if the string has repeats more than twice:

function checkStr(str) {
    str = str.replace(/\s+/g,"_");
    return /(\S)(\1{2,})/g.test(str);
}
like image 153
Billy Avatar answered Oct 20 '22 19:10

Billy


You can use this function:

function hasRepeatedLetters(str) {
    var patt = /^([a-z])\1+$/;
    var result = patt.test(str);
    return result;
}
like image 39
melhosseiny Avatar answered Oct 20 '22 18:10

melhosseiny


Use regular expressions:

var hasDuplicates = (/([a-z])\1/i).test(str)

Or if you don't want to catch aA and the likes

var hasDuplicates = (/([a-zA-Z])\1/).test(str)

Or, if you've decided you want to clarify your question:

var hasDuplicates = (/^([a-zA-Z])\1+$/).test(str)
like image 40
Eric Avatar answered Oct 20 '22 17:10

Eric


Try using this

checkRepeat = function (str) {
    var repeats = /(.)\1/;
    return repeats.test(str)
}

Sample usage

if(checkRepeat ("aaaaaaaa"))
alert('Has Repeat!')
like image 45
DeveloperX Avatar answered Oct 20 '22 19:10

DeveloperX


function check(str) {
    var tmp = {};
    for(var i = str.length-1; i >= 0; i--) {
        var c = str.charAt(i);
        if(c in tmp) {
            tmp[c] += 1;
        }
        else {
            tmp[c] = 1;
        }
    }
    var result = {};
    for(c in tmp) {
        if(tmp.hasOwnProperty(c)) {
            if(tmp[c] > 1){
                result[c] = tmp[c];
            }
        }
    }
    return result;
}

then you can check the result to get the repeated chars and their frequency. if result is empty, there is no repeating there.

like image 45
wong2 Avatar answered Oct 20 '22 18:10

wong2