get/change/remove URL parameters with jQuery?
18,175
Its easy to do by pure JS.
See this code from www.samaxes.com
var queryParameters = {}, queryString = location.search.substring(1),
re = /([^&=]+)=([^&]*)/g, m;
while (m = re.exec(queryString)) {
queryParameters[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
}
// Add new parameters or update existing ones
queryParameters['newParameter'] = 'new parameter';
queryParameters['existingParameter'] = 'new value';
location.search = $.param(queryParameters);
Its not flawless. But at least it can give you some idea.
Update 1:
Here is a function I wrote for another answer (cant remember). It works perfect.
Comments
-
Alex almost 2 years
I was looking over this question and searching google but I didn't find any update, so I am wondering if any of you know anything more recent because the last update on
https://github.com/blairmitchelmore/jquery.plugins was in 2009 and 2010 on https://github.com/cowboy/jquery-bbq
Or any other ideas? I need to add/change/remove parameters to my url
-
Hacknightly over 12 yearsYou'd like to alter the URL after having a loaded page?
-
Alex over 12 yearsyes... exactly, after the page has been loaded
-
Hacknightly over 12 yearsThis is tough to do, mainly because of the security issues involved. Are you unable to use either of the plugins you linked to? I'd imagine these would only manipulate the hash value.
-
Alex over 12 yearsi didn't tried them out because I am looking first for a more recent version to see if something... if not than I will see if they work. From 2009 to 2012 something better could've appeared
-
simon over 12 yearsManipulating query parameters is such a basic thing that it doesn't hardly matter whether the code is brand new or several years old.
-
-
Hacknightly over 12 yearsWouldn't location.search reload the page? I suppose this is Ok if that works for the op. I figured that a reload was undesirable.
-
Shiplu Mokaddim over 12 yearsNo.
location.search
contains the query string with?
added. Its a string. -
Hacknightly over 12 yearsTyping location.search = "foobar" into the console causes a page reload.
-
Shiplu Mokaddim over 12 years@hackNightly Yes. it'll reload the page. In fact OP want to change the param of query string so that it reloads.
-
Hacknightly over 12 yearsOh, ok, that makes more sense. Good call.
-
Alex over 12 yearsyes, but this is used only to set... not to get the value of an existing one... right?
-
Shiplu Mokaddim over 12 years@w0rldart If value can not be get how can it be set?
queryParameters['existingParameter']
gets value of parameterexistingParameter
.