Jump to content

Replace string function not working properly


jmfekete

Recommended Posts

Hi,I saw a snippet of code in Javascript for replacing space characters with another character. I have tried using it in a function() but my web pages is not working because of the while loop I've added.I have 2 text boxes on my page and want to replace any spaces in the string with "+".The code that I have found on this site is as follows:var loopProtect = 0;while(str.indexOf(" ") != -1 && loopProtect < str.length){str = str.replace(\ \,"+");loopProtect++;}Thanks!

Link to comment
Share on other sites

hmmm. no luck.Here's some of my code to help you understand what's going on a little more:<script type="text/javascript"> function sendSearch(){var param1 = document.getElementById('param1');var param2 = document.getElementById('param2');var theForm = document.forms[0]; --> This is where i want to add the bit of code to replace " " with "+". theForm.action += "&searchTerm=" + param1.value + "&zipcode=" + param2.value;theForm.submit();}</script></head><body class="pageBG"><form name="search" method="post" action="http://blahblah/blah.aspx?" id="search"><table width="52%" border="0" align="center" name="tblInfo" class="tblProp"><tr><td class="TLHeading" colspan="3">TrueLocal Web Assignment</td></tr><tr><td width="42%"><input name="param1" type="text" id="param1" /></td><td width="39%"><input name="param2" type="text" id="param2" /></td><td width="19%" align="center"><input name="Search" type="button" id="Search" value="Search" onClick="sendSearch()"></td></tr><tr><td class="textContent">What are you looking for?</td><td class="textContent">Where are you looking for it?</td><td></td></tr></table></form>So how can I write code to search through param1 for spaces in the text?Thanks!

Link to comment
Share on other sites

That while loop worked for me. Here's how you might incorporate it into your script:

<script type="text/javascript"> function sendSearch(){var param1 = document.getElementById('param1');var param2 = document.getElementById('param2');var theForm = document.forms[0];// Here is where you strip the spaces and replace it with '+'s //param1.value = stripSpaces(param1.value);param2.value = stripSpaces(param2.value);theForm.action += "&searchTerm=" + param1.value + "&zipcode=" + param2.value;theForm.submit();}// Here is a new stripSpaces function using your previous code:function stripSpaces(str){  var loopProtect = 0;  while(str.indexOf(" ") != -1 && loopProtect < str.length)  {	str = str.replace(" ","+");	loopProtect++;  }  return str;}</script>

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...