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

前端 未结 7 1936
没有蜡笔的小新
没有蜡笔的小新 2021-01-17 16:01

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

\"aaaaa\"

How can I do t

7条回答
  •  逝去的感伤
    2021-01-17 16:12

    I solved that using a for loop, not with regex

    //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))

提交回复
热议问题