JavaScript replaceAll function
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: development, javascript, security.