Constructing a URL with parameters using jQuery

JavascriptJquery

Javascript Problem Overview


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)

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

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

Solution 3 - Javascript

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

Solution 4 - Javascript

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

Solution 5 - Javascript

You can try this.

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

Solution 6 - Javascript

if (myUrl.indexOf("?") != -1){
    // contains query string
}
else
{
    // doesn't
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlfredo OsorioView Question on Stackoverflow
Solution 1 - JavascriptJesse PollakView Answer on Stackoverflow
Solution 2 - JavascriptepascarelloView Answer on Stackoverflow
Solution 3 - JavascriptAndrew HareView Answer on Stackoverflow
Solution 4 - JavascriptEsailijaView Answer on Stackoverflow
Solution 5 - JavascriptShankarSangoliView Answer on Stackoverflow
Solution 6 - JavascriptOmar SteweyView Answer on Stackoverflow