Adding Query Parameters to URL using Google Apps Script

Gists

Updated on February 5, 2024

This is for adding the query parameters to the URL. These scripts can be also used for Javascript. When I created an endpoint with some query parameters, I had used the scripts of various patterns every time. Today, I prepared this sample script to unify them. If this is also useful for you, I’m glad.

Sample script (With V8 runtime):

String.prototype.addQuery = function (obj) {
  return (this == "" ? "" : `${this}?`) + Object.entries(obj).flatMap(([k, v]) => Array.isArray(v) ? v.map(e => `${k}=${encodeURIComponent(e)}`) : `${k}=${encodeURIComponent(v)}`).join("&");
}


function myFunction1() {
  const url = "https://sampleUrl";
  const query = {
    query1: ["value1A", "value1B", "value1C"],
    query2: "value2A, value2B",
    query3: "value3A/value3B",
  };
  const endpoint = url.addQuery(query);
  console.log(endpoint); // https://sampleUrl?query1=value1A&query1=value1B&query1=value1C&query2=value2A%2C%20value2B&query3=value3A%2Fvalue3B
}

// In this case, only the query parameter is exported. This value can be used for requesting with Form data.
function myFunction2() {
  const url = "";
  const query = {
    query1: ["value1A", "value1B", "value1C"],
    query2: "value2A, value2B",
    query3: "value3A/value3B",
  };
  const endpoint = url.addQuery(query);
  console.log(endpoint); // query1=value1A&query1=value1B&query1=value1C&query2=value2A%2C%20value2B&query3=value3A%2Fvalue3B
}

Sample script (Without V8 runtime):

String.prototype.addQuery = function (obj) {
  return this + Object.keys(obj).reduce(function (p, e, i) {
    return p + (i == 0 ? "?" : "&") +
      (Array.isArray(obj[e]) ? obj[e].reduce(function (str, f, j) {
        return str + e + "=" + encodeURIComponent(f) + (j != obj[e].length - 1 ? "&" : "")
      }, "") : e + "=" + encodeURIComponent(obj[e]));
  }, "");
}


function myFunction() {
  var url = "https://sampleUrl";
  var query = {
    query1: ["value1A", "value1B", "value1C"],
    query2: "value2A, value2B",
    query3: "value3A/value3B",
  };
  var endpoint = url.addQuery(query);
  Logger.log(endpoint);
}

Result:

Both sample scripts return the following URL including the query parameters.

https://sampleUrl?query1=value1A&query1=value1B&query1=value1C&query2=value2A%2C%20value2B&query3=value3A%2Fvalue3B

 Share!