Javascript String sub(pattern, replacement, count)

Description

Javascript String sub(pattern, replacement, count)


String.prototype.sub = function(pattern, replacement, count) {
 replacement = this.gsub.prepareReplacement(replacement);
 count = count === undefined ? 1 : count;

 return this.gsub(pattern, function(match) {
  if (--count < 0) return match[0];
  return replacement(match);
 });//from w ww.  j a v a  2  s.  c  om
};

Javascript String sub(pattern, replacement, count)

//= require "String/gsub"

String.prototype.sub = function(pattern, replacement, count) {
  var replacer = Object.isFunction(replacement) ?
    replacement ://from w w w.  j a  va2 s. co  m
    function(){ return replacement };

  count = Object.isUndefined(count) ? 1 : count;

  return this.gsub(pattern, function(match) {
    if (--count < 0) return match[0];
    return replacer(match);
  });
}



PreviousNext

Related