Get character occurence count along with character in a string 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&lt;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;
    }
}
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);