Home > JavaScript > JavaScript Replace All

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) );
Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • LinkedIn
  • Live
  • MySpace
  • Reddit
  • StumbleUpon
Categories: JavaScript Tags:
  1. No comments yet.
  1. No trackbacks yet.