Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Replace function 1

Status
Not open for further replies.

kathyc20

Programmer
Mar 7, 2001
96
CA
I have the following code and would like to do a global replace of chars in a string but it only replaces the first occurrence. How do I get it to replace all occurrences?


sBadChars[0] = "+";
sBadChars[1] = "%2B";
sBadChars[2] = "%20";
sBadChars[3] = "%2520";
sBadChars[4] = "%22";

for (iCount = 0; iCount < sBadChars.length; iCount++)
{
iFound = sTemp.indexOf(sBadChars[iCount])

if (iFound > -1)
{
sFinal = sTemp.replace(sBadChars[iCount], " ");
}
}

return sFinal;
 
Your loop only loops through each array element.
indexOf only finds the first instance of the item so I setup a while loop that will continue performing the replace of that text until none remain then it loops to your next array element.

Note that it is now returning sTemp not sFinal. The way it was setup sTemp would never get updated, only sFinal so every iteration of the loop it would be starting over with the original sTemp string and you would never get anywhere.

Code:
for (iCount = 0; iCount < sBadChars.length; iCount++)
{
  while (sTemp.indexOf(sBadChars[iCount]) != -1)
  {
    sTemp = sTemp.replace(sBadChars[iCount], " ");
  }
  return sTemp;
}

Google, you're my hero!
 
An alternative is this.
[tt]
var rx=new RegExp("(\\"+sBadChars.join("|\\")+")","g");
return sTemp.replace(rx," ");
[/tt]
It looks general, but actually, it is not as general as it looks. It is based on some data made known to scripter on the what appears in sBadChars.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top