Search code examples
javascriptstringduplicatescharacter

Reducing duplicate characters in a string to a given minimum


I was messing around with the first question here: Reduce duplicate characters to a desired minimum and am looking for more elegant answers than what I came up with. It passes the test but curious to see other solutions. The sample tests are:

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

and my solution (that passes these tests):

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

Solution

  • Just use regular expressions.

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