Skip to content

Instantly share code, notes, and snippets.

@tanaikech
Last active November 8, 2021 08:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tanaikech/34437522f3ce777bd060458b9cc02bdf to your computer and use it in GitHub Desktop.
Save tanaikech/34437522f3ce777bd060458b9cc02bdf to your computer and use it in GitHub Desktop.
Parsing Query Parameters from URL using Google Apps Script

Parsing Query Parameters from URL using Google Apps Script

This is a sample script for parsing query parameters from an URL using Google Apps Script. Also this can be used at Javascript. The process cost becomes a bit lower than that of the script using the regular expression.

Sample script

function parseQuery(url) {
  var query = url.split("?")[1];
  if (query) {
    return query.split("&")
    .reduce(function(o, e) {
      var temp = e.split("=");
      var key = temp[0].trim();
      var value = temp[1].trim();
      value = isNaN(value) ? value : Number(value);
      if (o[key]) {
        o[key].push(value);
      } else {
        o[key] = [value];
      }
      return o;
    }, {});
  }
  return null;
}

// Please run this function when you test this script.
function main() {
  var url = "https://sampleUrl.com/sample?key1=value1&key2=value2&key1=value3&key3=value4&key2=value5";
  var res = parseQuery(url);
  Logger.log(res);
}

Result

{
  "key1": [
    "value1",
    "value3"
  ],
  "key2": [
    "value2",
    "value5"
  ],
  "key3": [
    "value4"
  ]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment