Javascript examples - removeElement() and replaceAll()
JavascriptI am currently working on a heavily Ajax-injected loan application project. This morning I created a couple of Javascript menthods that I thought might be useful to others. First is one named replaceAll() that will replace all instances of a substring within a string. Secondly is a removeElement() function that will remove a DOM element based on its ID. I am sure that some Javascript gurus out there are going to correct me on my approach, but these are functional and will hopefully save someone some time.
First is my:
function replaceAll(OldString,FindString,ReplaceString) {
var SearchIndex = 0;
var NewString = "";
while (OldString.indexOf(FindString,SearchIndex) != -1) {
NewString += OldString.substring(SearchIndex,OldString.indexOf(FindString,SearchIndex));
NewString += ReplaceString;
SearchIndex = (OldString.indexOf(FindString,SearchIndex) + FindString.length);
}
NewString += OldString.substring(SearchIndex,OldString.length);
return NewString;
}
Next up is:
function removeElement(id) {
var Node = document.getElementById(id);
Node.parentNode.removeChild(Node);
}
If anyone has a better approach for either of these, I am all ears.
EDIT:
That didn't take long! Richard Leggett posted a much cleaner solution to replaceAll() in the comments below. Just to make sure no one misses it, I am adding it here:
function replaceAll( str, searchTerm, replaceWith, ignoreCase ) {
var regex = "/"+searchTerm+"/g";
if( ignoreCase ) regex += "i";
return str.replace( eval(regex), replaceWith );
}





Loading....