Skip to content

Instantly share code, notes, and snippets.

@UnitedWithCode
Forked from tanaikech/submit.md
Created June 4, 2021 11:02
Show Gist options
  • Save UnitedWithCode/fb0ddc5959900fec79fb949ead199517 to your computer and use it in GitHub Desktop.
Save UnitedWithCode/fb0ddc5959900fec79fb949ead199517 to your computer and use it in GitHub Desktop.
Adding Query Parameters to URL using Google Apps Script

Adding Query Parameters to URL using Google Apps Script

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment