Javascript String gsub(pattern, replacement)
String.prototype.gsub = function(pattern, replacement) { var result = '', source = this, match; replacement = arguments.callee.prepareReplacement(replacement); while (source.length > 0) { if (match = source.match(pattern)) { result += source.slice(0, match.index); result += String.interpret(replacement(match)); source = source.slice(match.index + match[0].length); } else {/* ww w . j av a 2 s.c o m*/ result += source, source = ''; } } return result; };
String.prototype.gsub = function(pattern, replacement) { var result = '', source = this, match, replacer; replacer = Object.isFunction(replacement) ? replacement :/*from w ww . j a v a 2 s .c o m*/ function(){ return replacement }; if (Object.isString(pattern)) pattern = RegExp.escape(pattern); while (source.length > 0) { if (match = source.match(pattern)) { result += source.slice(0, match.index); result += replacer(match); source = source.slice(match.index + match[0].length); } else { result += source; source = ''; } } return result; };