Get character occurence count along with character in a string
I don't see any problem in your code except using of equality and inequality operators. Use strict equality(===) &amp; 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);