I want to get total count of consecutive repeated characters and numbers in a string.
For example :
const value = '11111aaaio222'
So the output should be 11
Explanation:
"1" repeating 5 times
"a" repeating 3 times
"2" repeating 3 times
I want to get total count of consecutive repeated characters and numbers in a string.
For example :
const value = '11111aaaio222'
So the output should be 11
Explanation:
"1" repeating 5 times
"a" repeating 3 times
"2" repeating 3 times
You can achieve it using a simple regex as well. Following regex matches 2 or more consecutive repeated characters.
/(.)\1+/g
(.)
- match any character\1+
- match the previously matched character again one or more timesconst regexp = /(.)\1+/g;
const str = '11111aaaio222';
const output = str.match(regexp).join('').length;
console.log(output)
const data = "11111aaaio222";
const result = Array.from(new Set([...data])).reduce((p, c) => {
let tc = 0;
[...data].forEach((ta, i) => {
if (ta === c && data[i + 1] === c) tc++;
})
tc && (p += tc + 1);
return p;
}, 0)
console.log(result);
To calculate the number of repetitions you can use regex:
([a-zA-Z\d])\1*
It will return groups of values like this [11111, aaa, i, o, 222]
.
Now we need to go through the array with reduce
and calculate the number of repeating elements. We also need to remove elements that are less than 2
const count = (str) => {
const regex = /([a-zA-Z\d])\1*/g;
const matches = str.match(regex) || [];
return matches.reduce((acc, item) => {
acc += item.length > 1 ? item.length : 0;
return acc
}, 0);
}
console.log(count("11111aaaio222"))
So we go through the array and sum up only those values that are repeated more than once.
current value: 0, item - 11111
current value: 5, item - aaa
current value: 8, item - i
current value: 8, item - o
current value: 8, item - 222
output value: 11
function duplicateCharCount(str) {
if(str) {
var obj = {};
for(let i = 0; i < str.length; i++) {
if(obj[str[i]]){
obj[str[i]] += obj[str[i]];
}else {
obj[str[i]] = 1;
}
}
console.log(obj);
}
}
duplicateCharCount("aabcdd");
https://gist.github.com/msaxena25/62d17a1c9b1e507f2eafd83fc7d54db0