(.) //match any character \1 //if it follow by the same character +{2 //more than 1 times /g //global $1 //is 1 time by $1$1 is 2 times reduceString('aaaabbbb', 2) reduceString('xaaabbbb', 2) reduceString('aaaabbbb', 1) reduceString('aaxxxaabbbb', 2) function reduceString(txt,num) { var canRepeat=['$1']; for (i=1;i<num;i++) { canRepeat.push('$1') } canRepeat = canRepeat.join(''); console.log(txt.replace(/(.)\1{2,}/g, canRepeat)) }