JavaScript String Replace All function
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: JavaScript, replace all, string
This entry was posted
on Friday, February 26th, 2010 at 11:18 am and is filed under JavaScript.
You can follow any responses to this entry through the RSS 2.0 feed.
You can leave a response, or trackback from your own site.
Feedback & Comments
No Responses