Wednesday, May 14, 2008

JavaScript Replace All function

 

// This function replaces all instances of findStr in oldStr with repStr.

function replaceAll(oldStr,findStr,repStr) {

  var srchNdx = 0;  // srchNdx will keep track of where in the whole line

                                    // of oldStr are we searching.

  var newStr = "";  // newStr will hold the altered version of oldStr.

  while (oldStr.indexOf(findStr,srchNdx) != -1)

                                    // As long as there are strings to replace, this loop

                                    // will run.

  {

    newStr += oldStr.substring(srchNdx,oldStr.indexOf(findStr,srchNdx));

                                    // Put it all the unaltered text from one findStr to

                                    // the next findStr into newStr.

    newStr += repStr;

                                    // Instead of putting the old string, put in the

                                    // new string instead.

    srchNdx = (oldStr.indexOf(findStr,srchNdx) + findStr.length);

                                    // Now jump to the next chunk of text till the next findStr.

  }

  newStr += oldStr.substring(srchNdx,oldStr.length);

                                    // Put whatever's left into newStr.

  return newStr;

}

No comments: