Constructing a URL with parameters using jQuery

I have for example the following URL stored in a global variable:

var myUrl = "http://mydomain.com/something?row=1";

Then a function has to add let's say another parameter called "column". How would that function add parameters to a pre-existing URL string using jQuery?

Example of the expected generated string:

"http://mydomain.com/something?row=1&column=9"

The problem is that myUrl could also be just:

var myUrl = "http://mydomain.com/something";

(Notice that there are not pre-existing parameters)


Check out the jQuery function .param(), that should do the trick.

http://api.jquery.com/jQuery.param/

You can then just create a function which appends the string generated by .param() to a url.


var myUrl = "http://mydomain.com/something";

function addQSParm(name, value) {
    var re = new RegExp("([?&]" + name + "=)[^&]+", "");

    function add(sep) {
        myUrl += sep + name + "=" + encodeURIComponent(value);
    }

    function change() {
        myUrl = myUrl.replace(re, "$1" + encodeURIComponent(value));
    }
    if (myUrl.indexOf("?") === -1) {
        add("?");
    } else {
        if (re.test(myUrl)) {
            change();
        } else {
            add("&");
        }
    }
}

console.log(myUrl);

addQSParm("foo", "asdf");
console.log(myUrl);

addQSParm("bar", "qwerty");
console.log(myUrl);

addQSParm("foo", "123");
console.log(myUrl);

jsFiddle


You don't need jQuery, use a function like this:

var buildUrl = function(base, key, value) {
    var sep = (base.indexOf('?') > -1) ? '&' : '?';
    return base + sep + key + '=' + value;
}

You would use it like this:

buildUrl('http://www.example.com/foo', 'test', '123');
buildUrl('http://www.example.com/foo?bar=baz', 'test', '123');