Skip to content
Advertisement

What is the best way to compose a link with GET parameters using JavaScript or jQuery

I want to compose a link with several GET parameters gathered from variables. For example:

link.php?param1=value1&param2=value2&param3=value3

In JavaScript, if I have variables var1, var2 and var3 set already to the corresponding values, I know the link can be composed by concatenating strings and the variables as follows:

url = "link.php?param1=" + var1 + "&param2=" + var2 + "&param3=" + var3;

Is there a cleaner or better way to do this? In jQuery, the AJAX requests function accept a data parameter that can be easily set as follows:

$.ajax({
  url: url,
  data:{
    param1: var1,
    param2: var2, 
    param3: var3
  }
});

Is there a similar way to compose the link but simply store it inside a variable instead of performing an ajax request?

I’m aware of jQuery’s .get() function, which, as the documentation mentions:

“Load data from the server using an HTTP GET request.”

I don’t want this, I just need to compose the link.

Advertisement

Answer

var makeFullUrl = function (url, params) {
    return [url, Object.keys(params || {}).map(function (key) {
        return encodeURIComponent(key) + '=' + encodeURIComponent(params[key]);
    }).join('&')].join('?');
};

that’s a function I made a while back (pre ES2015) – call it with the base URL as parameter 1, and an object like

{
    param1Name: param1Value,
    param2Name: param2Value
}

Here it is for ES2015, for laffs

var makeFullUrl = (url, params) => [url, Object.keys(params || {}).map(key => encodeURIComponent(key) + '=' + encodeURIComponent(params[key])).join('&')].join('?');
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement