views:

265

answers:

1

Hey guys,

how do i write a function in javascript that can get the current url eg:

http://www.blahblah.com/apps/category.php?pg=1&catId=3021

and depending on a user selection choice, appends another parameter to the url like:

http://localhost/buyamonline/apps/category.php?pg=1&catId=3021&limit=5

but heres the catch:

Everytime the user selects a diff choice, I dont want to keep appending stuff like

http://localhost/buyamonline/apps/category.php?pg=1&catId=3021&limit=5&limit=10 and so on.

I want to always replace add it if there is no limit parameter or replace the value if there is one.

I was trying to accomplish this using sprintf but failed.

i was doing like so:

var w = document.mylimit.limiter.selectedIndex;
var url_add = document.mylimit.limiter.options[w].value;
var loc = window.location.href;
window.location.href = sprintf(loc+"%s="+%s, "&limit", url_add);
+1  A: 

Updated with regular expression solution implemented in JS.

  1. You can use a regular expression using JavaScript replace() Method
  2. You can use build the entire url each time rather than just appending a parameter
  3. You can parse the url into it's parts before appending the parameter

Which would you prefer?

For #1: The following should do the trick. Note though, there are issues with using regular expressions for parsing urls. (Ref: stackoverflow.com/questions/1842681/…)

<script type="text/javascript">
  var pattern = "&limit(\=[^&]*)?(?=&|$)|^foo(\=[^&]*)?(&|$)";
  var modifiers = "";
  var txt=new RegExp(pattern,modifiers);
  var str="http://localhost/buyamonline/apps/category.php?pg=1&amp;catId=3021&amp;limit=5";
  document.write(str+"<br/>");
  var replacement = "&limit=10";
  document.write(str.replace(txt, replacement));
</script>
hinghoo
regex with javascript replace method i think should do.
Afamee
thanks everybody i got the answer.
Afamee