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

3
  • jsfiddle.net/4dw8gh9j seems to work for me if I hard-code your example. Are you sure window.location.href is what you expect? Commented Dec 19, 2014 at 20:45
  • @dckuehn it didnt work , http://jsfiddle.net/4dw8gh9j/1/ as i said it duplicates when it same id . Commented Dec 19, 2014 at 20:50
  • sorry, I often read too quickly for my own good. Commented Dec 19, 2014 at 21:12

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.