Javascript Replace All

As I mentioned in one of my previous posts, Javascript has its own replace function that, when used many times, you would have to resort using a / slash followed by options case insensitive and/or global and enclosing them to the search keyword, some cases may not be applicable to use that function. I scoured the net and found this neat function by Dave Shuck taken from this link.

The problem that I encountered was when I used Javascript’s replace() function with a search keyword that’s dynamic. If say, I want to use a search keyword like photo1 and photo2 and photo3 and place that in a for loop, doing it like this

var str = 'this is photo1 and photo2 and photo3';
for (i=0; i<3; i++) {
  alert(str.replace(/photo?/ig, '<replaced>'));
}

Notice the question mark i placed? I also tried to use the eval() function to see if appending the variable i would make it work. It didn’t. In the end, I decided to go look for a replaceAll() function in Javascript. At least I don’t have to make one anymore he he he. Here’s the function.

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;
}

Donations appreciated. Every little $ helps. Or click Google +1

Related Posts with Thumbnails

Leave a Reply

Spam protection by WP Captcha-Free