如何确定字符串是否包含重复字母序列

时间:2011-05-30 13:08:12

标签: javascript regex

使用JavaScript,我需要检查给定字符串是否包含重复字母序列,如下所示:

  

“AAAAA”

我该怎么做?

7 个答案:

答案 0 :(得分:12)

使用正则表达式:

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

或者如果你不想抓住aA和喜欢的

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

或者,如果您决定要澄清您的问题:

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

答案 1 :(得分:9)

您可以使用此功能:

function hasRepeatedLetters(str) {
    var patt = /^([a-z])\1+$/;
    var result = patt.test(str);
    return result;
}

答案 2 :(得分:3)

尝试使用此

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

样本用法

if(checkRepeat ("aaaaaaaa"))
alert('Has Repeat!')

答案 3 :(得分:2)

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;
}

然后您可以检查结果以获得重复的字符及其频率。如果结果为空,则不会重复。

答案 4 :(得分:1)

这将检查字符串是否重复两次以上:

function checkStr(str) {
    str = str.replace(/\s+/g,"_");
    return /(\S)(\1{2,})/g.test(str);
}

答案 5 :(得分:0)

var char = "abcbdf..,,ddd,,,d,,,";
var tempArry={};

for (var i=0; i < char.length; i++) {
    if (tempArry[char[i]]) {
        tempArry[char[i]].push(char[i]);
    } else {
        tempArry[char[i]] = [];
        tempArry[char[i]].push(char[i]);
    }
}

console.log(tempArry);

这甚至会返回重复字符的数量。

答案 6 :(得分:0)

我使用 for循环解决了问题,而不是使用正则表达式

&#13;
&#13;
//This check if a string has 3 repeated letters, if yes return true, instead return false
//If you want more than 3 to check just add another validation in the if check

function stringCheck (string) {
    for (var i = 0; i < string.length; i++)
        if (string[i]===string[i+1] && string[i+1]===string[i+2]) 
            return true
    
    return false 	
}
var str1 = "hello word" //expected false
var str2 = "helllo word" //expredted true
var str3 = "123 blAAbA" //exprected false
var str4 = "hahaha haaa" //exprected true

console.log(str1, "<==", stringCheck(str1))
console.log(str2, "<==", stringCheck(str2))
console.log(str3, "<==", stringCheck(str3))
console.log(str4, "<==", stringCheck(str4))
&#13;
&#13;
&#13;

相关问题