doniyor
doniyor

Reputation: 37856

javascript - simple but viral logical issue

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!

Upvotes: 0

Views: 51

Answers (1)

georg
georg

Reputation: 214949

This

url = url.replace(/([&?]sortterm=)[^&]*/, "$1" + sortterm)

Upvotes: 2

Related Questions