JavaScript String Replace All function

By Akbar

JavaScript provides the basic functions for string and other operations, but one needs lot more when working on some complex routines. Fortunately, the JavaScript prototype extension model helps us make custom functions available to all core objects of that type.

Anyway, coming back to point. JavaScript provides a string replace function, but it only replace the first found instance of the “find” string. Here is a quick prototype function for string which adds the support for “Replace All” in all JavaScript string functions.


// Replace all occurances of the given "find" string with the replace string
String.prototype.replaceAll = function(find, replace) { var regExp = new RegExp(find, "g"); return this.replace(regExp, replace); }

The code is self explanatory and once defined, can be used on all JavaScript string type variables.

If you have have any questions or suggestions, do let me know.

Tags: , ,