Skip to content

Instantly share code, notes, and snippets.

@Eyad-Bereh
Last active May 9, 2019 22:34
Show Gist options
  • Save Eyad-Bereh/598cfc13097a60328f0266fac36da981 to your computer and use it in GitHub Desktop.
Save Eyad-Bereh/598cfc13097a60328f0266fac36da981 to your computer and use it in GitHub Desktop.
A JavaScript function to obtain GET parameters from a URL
//nodejs v4.2.6
'use strict'; // needed in nodejs v4.2.6 to enable "let" keyword
function GetURLParameters(url) { // url to provide as string
let parameters_string = url.split("?")[1]; // all parameters comes after "?"
let parameters = parameters_string.split("&"); // split to pairs of key/value
let parameters_object = {}; // the object which will contain those pairs
for (let i = 0; i < parameters.length; i++) {
let key = parameters[i].split("=")[0]; // get the key
let value = parameters[i].split("=")[1]; // get the value
parameters_object[key] = value; // store the pair
}
parameters_object = JSON.stringify(parameters_object); // convert the parameters object into a JSON string
return parameters_object;
}
console.log(GetURLParameters("https://www.example.com/index.php?key1=value1&key2=value2")); // returns '{"key1":"value1","key2":"value2"}'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment