Adding Query Parameters to URL using Google Apps Script

Gists

This is for adding the query parameters to the URL. This sample script is prepared by ES5. So this 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 :

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 :

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

 Share!