javascript - Reducing duplicate characters in a string to a given minimum -


i messing around first question here: reduce duplicate characters desired minimum , looking more elegant answers came with. passes test curious see other solutions. sample tests are:

reducestring('aaaabbbb', 2) 'aabb'   reducestring('xaaabbbb', 2) 'xaabb'  reducestring('aaaabbbb', 1) 'ab'     reducestring('aaxxxaabbbb', 2)  'aaxxaabb' 

and solution (that passes these tests):

reducestring = function(str, amount) {   var count = 0;   var result = '';   (var = 0; < str.length; i++) {     if (str[i] === str[i+1]) {       count++;       if (count < amount) {         result += str[i];       }     } else {       count = 0;       result += str[i];     }    };   return result; } 

just use regular expressions.

var reducestring = function (str, amount) {     var re = new regexp("(.)(?=\\1{" + amount + "})","g");     return str.replace(re, ""); }