admin管理员组

文章数量:1290949

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:


to bee:


or, if a parameter already exists, then add a second parameter:

;qa=newParam

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./about

to bee:

http://www.mysite./about?qa=newParam

or, if a parameter already exists, then add a second parameter:

http://www.mysite./about?qa=oldParam&qa=newParam
Share Improve this question asked Mar 10, 2014 at 21:44 cc-testcc-test 431 gold badge3 silver badges11 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 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)
};

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.

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";
}

本文标签: javascriptHow do you add a parameter to a URL and reload the pageStack Overflow