How to determine if a string contains a sequence of repeated letters
Using JavaScript, I need to check if a given string contain开发者_如何学Cs a sequence of repeated letters, like this:
"aaaaa"
How can I do that?
You can use this function:
function hasRepeatedLetters(str) {
var patt = /^([a-z])\1+$/;
var result = patt.test(str);
return result;
}
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)
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);
}
Try using this
checkRepeat = function (str) {
var repeats = /(.)\1/;
return repeats.test(str)
}
Sample usage
if(checkRepeat ("aaaaaaaa"))
alert('Has Repeat!')
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.
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))
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);
This will even return the number of repeated characters also.
精彩评论