user1036103
user1036103

Reputation: 23

I want to find replace one url query parameter with jquery

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

Upvotes: 0

Views: 481

Answers (2)

charlietfl
charlietfl

Reputation: 171669

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/

Upvotes: 1

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 .

Upvotes: 2

Related Questions