var str = 'AAAABBBCCXYZDDDDEEEFFFAAAAAABBBBBBBBBBBBBBBBBBBBBBBBBBBBbbb'; function rle(s) { return s.replace(/(.)\1*/g, function (m, c) { return c + (m.length > 1 ? m.length : ''); }); } alert(rle(str))