JavaScript replaceAll function

September 29th, 2009 by alex

Certain JS implementations, notably IBMJS or Lotus Notes’s JS, are still missing some of the most basic string manipulation functionality. That is an ability replace all occurrences of a substring in a string. This fact, lack of proper RegExp implementation (e.g. /\\/g does not work) and an improper split/join functionality (e.g “bab”.split(“b”).join(“z”) results in “za” with last “z” omitted) means that a custom function is required. Here is the function you could use to do just that, that does not suffer from shortcomings of other methods found on the web (for example falling into an infinite loop when escaping backslashes, e.g. substituting “\” with “\\”)

function replaceAll(text, strA, strB) {
sidx=0; restext="";
while ((eidx=text.indexOf(strA,sidx)) != -1) {
restext += text.substring(sidx,eidx)+strB;
sidx=eidx+strA.length;
}
return restext+text.substring(sidx,text.length);
}

Run as
newstring=replaceAll(origstring, string-to-replace, string-to-replace-with);

Tagged with: , , .

Leave a Reply

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.

Ivkin.Net :: where tech and candy come together