Better gsub method for Prototype library.
Today I needed to use the method gsub implemented by the Prototype, the javascript library used by Rails. I perceived that it was a little different of ruby’s one.
The ruby method return a array if called without replacement string, but prototype’s doesn’t.
So, I wrote my own gsub method to be used with prototype that return an array when called without replacement string.
Enjoy!
[js] // Code by Rafael Lima (http://rafael.adm.br) Object.extend(String.prototype, { gsub: function(pattern, replacement) { var result = new Array(), source = this, match; var replace = (undefined != replacement) if (replace) { replacement = arguments.callee.prepareReplacement(replacement); }
while (source.length > 0) {
if (match = source.match(pattern)) {
result[result.length] = source.slice(0, match.index) + ((replace) ? (replacement(match) || '').toString() : match[0] );
source = source.slice(match.index + match[0].length);
} else {
result[result.length] = source, source = '';
}
}
return (replace) ? result.join('') : result; } }); [/js]