1

I got this function from here in stack to replace url parameters like that :

function replaceUrlParam(paramName, paramValue){
    var currentUrl = window.location.href;
    var pattern = new RegExp('('+paramName+'=).*?(&|$)') 
    var newUrl = currentUrl.replace(pattern,'$1' + paramValue + '$2');
    if(newUrl == currentUrl){
        newUrl = newUrl + (newUrl.indexOf('?')>0 ? '&' : '?') + paramName + '=' + paramValue 
    }
    window.history.pushState('',document.title,newUrl);
    return newUrl;
}

www.mysite.com/index.php?id=14&&cat=20

and i use it like that:

replaceUrlParam('id', 15);

like that works fine.

But the problem is it duplicates the id if i use same id which is in the url like that.

replaceUrlParam('id', 14)--will give--->www.mysite.com/index.php?id=14&&cat=20&&id=14

How can i change this function to not give duplicates when its same id ? Thanks

fiddle here

Community
  • 1
  • 1
Scooter Daraf
  • 525
  • 7
  • 23
  • http://jsfiddle.net/4dw8gh9j/ seems to work for me if I hard-code your example. Are you sure `window.location.href` is what you expect? – dckuehn Dec 19 '14 at 20:45
  • @dckuehn it didnt work , [http://jsfiddle.net/4dw8gh9j/1/](http://jsfiddle.net/4dw8gh9j/1/) as i said it duplicates when it same id . – Scooter Daraf Dec 19 '14 at 20:50
  • sorry, I often read too quickly for my own good. – dckuehn Dec 19 '14 at 21:12

2 Answers2

2

The if statement in the function explains everything. If the url hasn't changed then it tacks the param/value onto the end. Sounds like you want to also check that the value isn't already in there, like:

if(newUrl == currentUrl && newUrl.indexOf(paramName+'='+paramValue) === -1) {
    //...
}

Here's an updated jsfiddle

Jack
  • 20,735
  • 11
  • 48
  • 48
1

www.mysite.com/index.php?id=14&&cat=20

and

replaceUrlParam('id', 14)

is trying to repalce id:14 with id:14. So in this case: newUrl == currentUrl will resolve to true.

newUrl = newUrl + (newUrl.indexOf('?')>0 ? '&' : '?') + paramName + '=' + paramValue

will find the index of the '?', which is 24, which is > 0.

So in the end you're doing this:

newUrl = www.mysite.com/index.php?id=15&&cat=20 + paramName + '=' + paramValue

In either scenario, if your (currentUrl == newUrl) == true your concatanation will end up either doing newUrl = newUrl + '&' + paramName + '=' + paramValue or newUrl = newUrl + '?' + paramName + '=' + paramValue

Either way will duplicate your value at the end.

dckuehn
  • 2,427
  • 3
  • 27
  • 37