Using JavaScript, I need to check if a given string contains a sequence of repeated letters, like this:
"aaaaa"
How can I do that?
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);
}
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With