I'm looking for the simplest way to add parameters to a URL and then reload the page via javascript/jquery. I'm trying to avoid any plugins. Essentially I want:
http://www.mysite.com/about
to become:
http://www.mysite.com/about?qa=newParam
or, if a parameter already exists, then add a second parameter:
http://www.mysite.com/about?qa=oldParam&qa=newParam
3 Answers 3
Here is a vanilla solution, it should work nicely for all cases (except wrong inputs of course).
function replace_search(name, value) {
var str = location.search;
if (new RegExp("[&?]"+name+"([=&].+)?$").test(str)) {
str = str.replace(new RegExp("(?:[&?])"+name+"[^&]*", "g"), "")
}
str += "&";
str += name + "=" + value;
str = "?" + str.slice(1);
// there is an official order for the query and the hash if you didn't know.
location.assign(location.origin + location.pathname + str + location.hash)
};
EDIT: if you want to add stuff and never remove anything the function is way smaller. I'm not very found of having multiple fields with different values but there is no specifications on that.
function replace_search(name, value) {
var str = "";
if (location.search.length == 0) {
str = "?"
} else {
str = "&"
}
str += name + "=" + value;
location.assign(location.origin + location.pathname + location.search + str + location.hash)
};
1 Comment
Have a look at Window.location (MDN) for information on window.location.
A quick and dirty solution is:
location += (location.search ? "&" : "?") + "qa=newParam"
It should work for your example, but misses some edge cases.
Comments
location.href will give you the current URL. You can then edit your query string and refresh the page by doing something like this:
if (location.href.indexOf("?") === -1) {
window.location = location.href += "?qa=newParam";
}
else {
window.location = location.href += "&qa=newParam";
}
2 Comments
<script> tag? In that case they would be executed when the page loads, causing a redirect. Is so, then try putting it in a function like @username’s solution and call it when you want to reload the page.