Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructing a URL with parameters using jQuery

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');

Keep everything in an object until you actually need a string.

First populate the object from some initial values:

var $_GET = location.search.substr(1).split("&").reduce( function( obj, val ){
    if( !val ) return obj;
    var pair = val.split("=");
    obj[pair[0]] = pair[1];
    return obj;
}, {} );

Considering initial url of: "http://mydomain.com/something?row=1&column=9"

$_GET['column'] = 5;

$.param( $_GET ); //"row=1&column=5"

Array#reduce


You can try this.

myUrl += ((myUrl.indexOf('?') == -1) ? '?' : '&');
myUrl += "column=9";