Working with JavaScript is always a little shady for me. I tend not to trust my JavaScript code at first glance, due to the differences in standards that browsers support, the a lack of a formal, scripting environment, and the kludgy approach to debugging. IE browsers support these standards, while non IE browsers support those, and in some cases both can agree. When working in JavaScript, community support becomes my biggest asset. For those searching for replace all functionality, I present this entry.
After using the JavaScript string's "replace" method, I noticed I was receiving unexpected results, specifically, the end result seemed to be partially complete. I was not sure where to place the blame, so I began debugging, only to find out the following.
The JavaScript string's "replace" method does not replace all occurrences within the string, unlike the .Net string.Replace(). It only replaces the first occurrence. Since the replace function would actually need to recurse the string as an array, searching for matches, and replacing them. JavaScript has not built this into their library. I am going to guess this is the same reason that XSLT does not have a replace function.
In any case, what can be done about the much needed replace all functionality missing in JavaScript? There are a few alternatives, and I present two. One idea would be to create a new function, "replaceAll()." In it, we would use a while loop, and iterate through the string searching for matches and replacing each. The user would pass in a string reference, the text to replace, and the text that will replace it.
function replaceAll(text, strA, strB)
{
while ( text.indexOf(strA) != -1)
{
text = text.replace(strA,strB);
}
return text;
}
Another approach involves using regular expressions within JavaScript. Regular expressions, while sometimes difficult to understand, are useful, and in a situation such as this, they reduce the need to write excess JavaScript code, therefore reducing possible errors (in theory). There are number of resources on the internet providing instructions, tutorials, and tools for using regular expressions. In the following code, my "replaceAll()" method will accomplish the same goal using the power of regular expressions.
function replaceAll(text, strA, strB)
{
return text.replace( new RegExp(strA,"g"), strB );
}
My wish would be for the JavaScript string's replace method to replace all instances of a string, not just one. In the meantime, here are two, easy to use methods, to finish what JavaScript started. One good resource using regular expressions in JavaScript, as well as with other languages, can be found at Regular-Expressions.info.