var s = 'AAAABBBCCXYZDDDDEEEFFFAAAAAABBBBBBBBBBBBBBBBBBBBBBBBBBBBbbb'; // A4B3C2XYZD4E3F3A6B28b3 function rle(s) { return s.replace(/(.)\1+/g, function(a, c) { return c + a.length }); } alert(rle(s))