HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptModerate

Get character occurence count along with character in a string

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
countoccurencewithcharactergetalongstring

Problem

I want to find character sequence count in a given string.

Sample Input: aaaabbbbaaacccbbb

Output: a4b4a3c3b3

My below function is working great and giving me the same result. but can this be optimized?

function getCharCount(str) {
    var result = str.charAt(0);
    var count = 1;
    if (str.length == 1) {
        result += count;
        return result;
    } else {
        for(var i=1;i<str.length;i++) {
            if(str.charAt(i) != str.charAt(i-1)) {
                result += count + str.charAt(i);
                count = 1;
            } else {
                count++;
            }
            if (i == str.length - 1) {
                result += count;
            }
        }
        return result;
    }
}

Solution

I don't see any problem in your code except using of equality and inequality operators. Use strict equality(===) & inequality(!==) operators.

I'll suggest to use RegEx.

.replace(/(.)\1*/g, function(m, $1) {
    return $1 + m.length;
})


The RegEx (.)\1* will match a single non-line-break character and check if that is followed by the same character any number of times. m here is the complete match and $1 is the first chaptured group value i.e. the character.



var res = 'aaaabbbbaaacccbbb'
.replace(/(.)\1*/g, function(m, $1) {
return $1 + m.length;
});
console.log(res);

Code Snippets

.replace(/(.)\1*/g, function(m, $1) {
    return $1 + m.length;
})

Context

StackExchange Code Review Q#148056, answer score: 12

Revisions (0)

No revisions yet.