0

I want to replace a dynamic url query parameter with another parameter.

Eg. like my url is:

http://www.mysite.com/209-0539.prd?pageLevel=&skuId=111-4567&sc_cmp=pcp_GSF_Batteries+%26+Electrical+Accessories_209-0539

I want to replace everything starting after

&sc_cmp=pcp_GSF_Batteries+%26+Electrical+Accessories_209-0539

and add something like & new Static string

My final url should look like:

http://www.mysite.com/209-0539.prd?pageLevel=&skuId=111-4567& new static string.

Thanks

2
  • Could this help? stackoverflow.com/a/10235376/733347 Commented Oct 20, 2012 at 14:53
  • you should first show us what you've tried so far. it will also help you to learn more Commented Oct 22, 2012 at 1:50

2 Answers 2

2

I recommend you to use the cool URI.js library, then it's as easy as:

var url = "http://www.mysite.com/209-0539.prd?pageLevel=&skuId=111-4567&sc_cmp=pcp_GSF_Batteries+%26+Electrical+Accessories_209-0539";

url = URI(url).removeSearch("sc_cmp").addSearch("newvar","newval");

// http://www.mysite.com/209-0539.prd?pageLevel=&skuId=111-4567&newvar=newval
alert(url);

See working demo .

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

Comments

1

If you don't want to include another library, following lets you add as many search items you want removed and add as many as you like without a lot of code

/* array of search keys to remove*/
var removeSearch = ['sc_cmp']; 

/* array of new search items*/
var newSearchitem = ['image=cool']; 
var url = location.href; 

var pageUrl = url.split('?')[0];

var urlSearch = url.split('?')[1].split('&');
/* store search items in array */
var newSearchArr = [];
/* loop over exisiting search items and store keepers*/
for (i = 0; i < urlSearch.length; i++) {
    var key = urlSearch[i].split('=')[0];
    if ($.inArray(key, removeSearch) == -1) {
        newSearchArr.push(urlSearch[i])
    }
}

$.merge(newSearchArr, newSearchitem);

var newUrl = pageUrl + '?' + newSearchArr.join('&')

DEMO: http://jsfiddle.net/9VPUX/

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.