Scooter Daraf
Scooter Daraf

Reputation: 535

Replace url parameters function

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

Upvotes: 1

Views: 237

Answers (2)

dckuehn
dckuehn

Reputation: 2475

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.

Upvotes: 1

Jack
Jack

Reputation: 21163

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

Upvotes: 2

Related Questions