0

I have a url:

domain.com/?page=2&show=10&sortterm=km

If I sort for the second time, url is becoming

domain.com/?page=2&show=10&sortterm=km&sortterm=km

What i want to do is:

1. see if url has "?" in it
2. if yes, 
  2.1. see if "sortterm" exists in url
  2.2. if yes, replace that "&sortterm=x" with new "&sortterm=y"
  2.3. if not, add "&sortterm=y"
3. if not
  3.1 add "?sortterm=y"

this is my code:

var url = String(window.location);
if(url.indexOf("?") !== -1){
  if(url.indexOf('sortterm') !== -1){
    var newurl = url +'&sortterm='+sortterm; 
   //^ but i need to replace here, and the value of sortterm can be different. 
  }
...
...

I am a bit stuck, pleas help!

doniyor
  • 36,596
  • 57
  • 175
  • 260

1 Answers1

2

This

url = url.replace(/([&?]sortterm=)[^&]*/, "$1" + sortterm)
georg
  • 211,518
  • 52
  • 313
  • 390