JavaScript Replace All
Here’s my version of the replaceAll() method for JavaScript. I doubt it’s faster than RegEx, but it was certainly fun to make.
String.prototype.replaceAll = function(s, r, n) { if( this.toString().indexOf(s) < n ) n = 0; if( !n ) return this.toString().split( s ).join( r ); var j = this.toString(); while( n-- ) { j = j.replace( s, r ); } return j; } var TestString = "I Love My Pie So Much, Don't You?"; // Usage console.log( TestString.replace("o", "*") ); console.log( TestString.replaceAll("o", "*", 2) );
Categories: JavaScript