How do I parse variables from URL in javascript? [duplicate] - javascript

This question already has answers here:
How can I get query string values in JavaScript?
(73 answers)
Closed 5 years ago.
Consider:
http://example.com/page.html?returnurl=%2Fadmin
For js within page.html, how can it retrieve GET parameters?
For the above simple example, func('returnurl') should be /admin.
But it should also work for complex query strings...

With the window.location object. This code gives you GET without the question mark.
window.location.search.substr(1)
From your example it will return returnurl=%2Fadmin
EDIT: I took the liberty of changing Qwerty's answer, which is really good, and as he pointed I followed exactly what the OP asked:
function findGetParameter(parameterName) {
var result = null,
tmp = [];
location.search
.substr(1)
.split("&")
.forEach(function (item) {
tmp = item.split("=");
if (tmp[0] === parameterName) result = decodeURIComponent(tmp[1]);
});
return result;
}
I removed the duplicated function execution from his code, replacing it a variable ( tmp ) and also I've added decodeURIComponent, exactly as OP asked. I'm not sure if this may or may not be a security issue.
Or otherwise with plain for loop, which will work even in IE8:
function findGetParameter(parameterName) {
var result = null,
tmp = [];
var items = location.search.substr(1).split("&");
for (var index = 0; index < items.length; index++) {
tmp = items[index].split("=");
if (tmp[0] === parameterName) result = decodeURIComponent(tmp[1]);
}
return result;
}

window.location.search will return everything from the ? on. This code below will remove the ?, use split to separate into key/value arrays, then assign named properties to the params object:
function getSearchParameters() {
var prmstr = window.location.search.substr(1);
return prmstr != null && prmstr != "" ? transformToAssocArray(prmstr) : {};
}
function transformToAssocArray( prmstr ) {
var params = {};
var prmarr = prmstr.split("&");
for ( var i = 0; i < prmarr.length; i++) {
var tmparr = prmarr[i].split("=");
params[tmparr[0]] = tmparr[1];
}
return params;
}
var params = getSearchParameters();
You can then get the test parameter from http://myurl.com/?test=1 by calling params.test.

You should use URL and URLSearchParams native functions:
let url = new URL("https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8&q=mdn%20query%20string")
let params = new URLSearchParams(url.search);
let sourceid = params.get('sourceid') // 'chrome-instant'
let q = params.get('q') // 'mdn query string'
let ie = params.has('ie') // true
params.append('ping','pong')
console.log(sourceid)
console.log(q)
console.log(ie)
console.log(params.toString())
console.log(params.get("ping"))
https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
https://polyfill.io/v2/docs/features/

tl;dr solution on a single line of code using vanilla JavaScript
var queryDict = {}
location.search.substr(1).split("&").forEach(function(item) {queryDict[item.split("=")[0]] = item.split("=")[1]})
This is the simplest solution. It unfortunately does not handle multi-valued keys and encoded characters.
"?a=1&a=%2Fadmin&b=2&c=3&d&e"
> queryDict
a: "%2Fadmin" // Overridden with the last value, not decoded.
b: "2"
c: "3"
d: undefined
e: undefined
Multi-valued keys and encoded characters?
See the original answer at How can I get query string values in JavaScript?.
"?a=1&b=2&c=3&d&e&a=5&a=t%20e%20x%20t&e=http%3A%2F%2Fw3schools.com%2Fmy%20test.asp%3Fname%3Dståle%26car%3Dsaab&a=%2Fadmin"
> queryDict
a: ["1", "5", "t e x t", "/admin"]
b: ["2"]
c: ["3"]
d: [undefined]
e: [undefined, "http://w3schools.com/my test.asp?name=ståle&car=saab"]
In your example, you would access the value like this:
"?returnurl=%2Fadmin"
> qd.returnurl // ["/admin"]
> qd['returnurl'] // ["/admin"]
> qd.returnurl[0] // "/admin"

A more fancy way to do it: :)
var options = window.location.search.slice(1)
.split('&')
.reduce(function _reduce (/*Object*/ a, /*String*/ b) {
b = b.split('=');
a[b[0]] = decodeURIComponent(b[1]);
return a;
}, {});

This one uses a regular expression and returns null if the parameter doesn't exist or doesn't have any value:
function getQuery(q) {
return (window.location.search.match(new RegExp('[?&]' + q + '=([^&]+)')) || [, null])[1];
}

I do it like this (to retrieve a specific get-parameter, here 'parameterName'):
var parameterValue = decodeURIComponent(window.location.search.match(/(\?|&)parameterName\=([^&]*)/)[2]);

Here I've made this code to transform the GET parameters into an object to use them more easily.
// Get Nav URL
function getNavUrl() {
// Get URL
return window.location.search.replace("?", "");
};
function getParameters(url) {
// Params obj
var params = {};
// To lowercase
url = url.toLowerCase();
// To array
url = url.split('&');
// Iterate over URL parameters array
var length = url.length;
for(var i=0; i<length; i++) {
// Create prop
var prop = url[i].slice(0, url[i].search('='));
// Create Val
var value = url[i].slice(url[i].search('=')).replace('=', '');
// Params New Attr
params[prop] = value;
}
return params;
};
// Call of getParameters
console.log(getParameters(getNavUrl()));

I have created a simple JavaScript function to access GET parameters from URL.
Just include this JavaScript source and you can access get parameters.
E.g.: in http://example.com/index.php?language=french, the language variable can be accessed as $_GET["language"]. Similarly, a list of all parameters will be stored in a variable $_GET_Params as an array. Both the JavaScript and HTML are provided in the following code snippet:
<!DOCTYPE html>
<html>
<body>
<!-- This script is required -->
<script>
function $_GET() {
// Get the Full href of the page e.g. http://www.google.com/files/script.php?v=1.8.7&country=india
var href = window.location.href;
// Get the protocol e.g. http
var protocol = window.location.protocol + "//";
// Get the host name e.g. www.google.com
var hostname = window.location.hostname;
// Get the pathname e.g. /files/script.php
var pathname = window.location.pathname;
// Remove protocol part
var queries = href.replace(protocol, '');
// Remove host part
queries = queries.replace(hostname, '');
// Remove pathname part
queries = queries.replace(pathname, '');
// Presently, what is left in the variable queries is : ?v=1.8.7&country=india
// Perform query functions if present
if (queries != "" && queries != "?") {
// Remove question mark '?'
queries = queries.slice(1);
// Split all the different queries
queries = queries.split("&");
// Get the number of queries
var length = queries.length;
// Declare global variables to store keys and elements
$_GET_Params = new Array();
$_GET = {};
// Perform functions per query
for (var i = 0; i < length; i++) {
// Get the present query
var key = queries[i];
// Split the query and the value
key = key.split("=");
// Assign value to the $_GET variable
$_GET[key[0]] = [key[1]];
// Assign value to the $_GET_Params variable
$_GET_Params[i] = key[0];
}
}
}
// Execute the function
$_GET();
</script>
<h1>GET Parameters</h1>
<h2>Try to insert some get parameter and access it through JavaScript</h2>
</body>
</html>

var getQueryParam = function(param) {
var found;
window.location.search.substr(1).split("&").forEach(function(item) {
if (param == item.split("=")[0]) {
found = item.split("=")[1];
}
});
return found;
};

Here is another example based on Kat's and Bakudan's examples, but making it a just a bit more generic.
function getParams ()
{
var result = {};
var tmp = [];
location.search
.substr (1)
.split ("&")
.forEach (function (item)
{
tmp = item.split ("=");
result [tmp[0]] = decodeURIComponent (tmp[1]);
});
return result;
}
location.getParams = getParams;
console.log (location.getParams());
console.log (location.getParams()["returnurl"]);

To get the parameters as a JSON object:
console.log(getUrlParameters())
function getUrlParameters() {
var out = {};
var str = window.location.search.replace("?", "");
var subs = str.split(`&`).map((si)=>{var keyVal = si.split(`=`); out[keyVal[0]]=keyVal[1];});
return out
}

If you don't mind using a library instead of rolling your own implementation, check out https://github.com/jgallen23/querystring.

This solution handles URL decoding:
var params = function() {
function urldecode(str) {
return decodeURIComponent((str+'').replace(/\+/g, '%20'));
}
function transformToAssocArray( prmstr ) {
var params = {};
var prmarr = prmstr.split("&");
for ( var i = 0; i < prmarr.length; i++) {
var tmparr = prmarr[i].split("=");
params[tmparr[0]] = urldecode(tmparr[1]);
}
return params;
}
var prmstr = window.location.search.substr(1);
return prmstr != null && prmstr != "" ? transformToAssocArray(prmstr) : {};
}();
Usage:
console.log('someParam GET value is', params['someParam']);

My solution expands on #tak3r's.
It returns an empty object when there are no query parameters and supports the array notation ?a=1&a=2&a=3:
function getQueryParams () {
function identity (e) { return e; }
function toKeyValue (params, param) {
var keyValue = param.split('=');
var key = keyValue[0], value = keyValue[1];
params[key] = params[key]?[value].concat(params[key]):value;
return params;
}
return decodeURIComponent(window.location.search).
replace(/^\?/, '').split('&').
filter(identity).
reduce(toKeyValue, {});
}

You can use the search function available in the location object. The search function gives the parameter part of the URL. Details can be found in Location Object.
You will have to parse the resulting string for getting the variables and their values, e.g. splitting them on '='.

If you are using AngularJS, you can use $routeParams using ngRoute module
You have to add a module to your app
angular.module('myApp', ['ngRoute'])
Now you can use service $routeParams:
.controller('AppCtrl', function($routeParams) {
console.log($routeParams); // JSON object
}

Related

Get Url string parameter as JSON object

I was wondering if it is possible to get the url parameter as JSON object using window object.
For ex. I have the url "/#/health?firstName=tom&secondName=Mike"
and get the value as {"firstName": "tom", "secondName": "Mike"}
I tried to explore the window object but could not find any help.
I think I can try parsing the string firstName=tom&secondName=Mike and convert this to json but this doesn't look like a great approach. BTW if there are smart way to parse, that too will be appreciated.
Please let me know if I should provide any more information.
In Angular you can get the URL with:
this.router.url
Once you've got the URL, you should use the very popular (14 mill downloads a week) npm qs module:
var qs = require('qs');
var obj = qs.parse('firstName=tom&secondName=Mike');
returns:
{
firstName: 'tom'
secondName: 'mike'
}
Using straight javascript first get the params and then convert them into an object:
<script type="text/javascript">
// params will be an object with key value pairs based on the url query string
var params = paramsToObject();
console.log(params);
// Get the parameters by splitting the url at the ?
function getParams() {
var uri = window.location.toString();
if (uri.indexOf("?") > 0) {
var params = uri.substring(uri.indexOf("?") + 1, uri.length);
return params;
}
return "";
}
// Split the string by & and then split each pair by = then return the object
function paramsToObject() {
var params = getParams().split("&");
var obj = {};
for (p in params) {
var arr = params[p].split("=");
obj[arr[0]] = arr[1];
}
return obj;
}
</script>
If using Angular:
You can use the qs npm module suggested in the answer by danday74.
const str = 'abc=foo&def=%5Bbar%5D&xyz=5'
// reduce takes an array and reduces it into a single value
const nameVal = str.split('&').reduce((prev, curr) => {
// see output here in console for clarity:
console.log('curr= ', curr, ' prev = ', prev)
prev[decodeURIComponent(curr.split('=')[0])] = decodeURIComponent(curr.split('=')[1]);
return prev;
}, {});
// invoke
console.log(nameVal);

Getting two query string parameters

I'm using the code below to get query parameters for a search in javascript. Is there any particular reason why this wouldn't be able to handle multiple parameters? I seem to be having trouble implementing it.
var params = [], hash;
var q = document.URL.split('?')[1];
if(q != undefined){
q = q.split('&');
for(var i = 0; i < q.length; i++){
hash = q[i].split('=');
params.push(hash[1]);
params[hash[0]] = hash[1];
}
}
You could potentially use a regex to get the params.
var test = 'example.com/index.html?param1=foo&param2=data#icouldhaveahashtoo';
var params = {};
test.replace(/[?&]([^=]+)[=]([^&#]+)/g, function(match, key, value){
params[key] = value;
return '';
});
console.log(params);
Seems your code works fine, however, it won't work properly with URL's with query parameters assigned more than one value (like http://example.com/page.php?param=foo&param=bar). Additionally, if one of the query string parameter names is length or something, that could do bad things to the params array - might be better to try a different container.
var params = [], hash;
var q = 'example.com/index.html?param1=foo&param2=data'.split('?')[1];
if(q != undefined){
q = q.split('&');
for(var i = 0; i < q.length; i++){
hash = q[i].split('=');
params.push(hash[1]);
params[hash[0]] = hash[1];
}
}
console.dir(params); // Array[2] 0: "foo" 1: "data" length: 2 param1: "foo" param2: "data" __proto__: Array[0]
I'd suggest having the params variable be an object, and skip the line params.push(hash[1]), because you can iterate over the properties using a for..in loop easily enough, and the order of the parameters shouldn't matter anyways. If there's more than one value for a parameter of a particular name, then the value of that parameter would be an array. For example, ?param=foo&param=bar would end up being parsed as { param: ["foo", "bar"] }.

Setting array key value pair JavaScript

So, I am having an issue and for the life of me I cannot seem to resolve it. It seems very basic, but I just cannot understand for the life of me why this code is not working.
My issue is, I am assigning a key value pair to an array, but the values DO NOT get assigned. Is it a variable scope issue?
Here is my code
function getcookie(cookiename){
var mycookies = []; // The cookie jar
var temp = document.cookie.split(";");
var key = "";
var val = "";
for(i=0;i<temp.length;i++){
key = temp[i].split("=")[0];
val = temp[i].split("=")[1];
mycookies[key] = val;
}
return mycookies[cookiename];
}
Trim your key because cookie strings look like this:
"__utma=250730393.1032915092.1427933260.1430325220.1430325220.1; __utmc=250730393; __utmz=250730393.1430325220.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); clicks=22; _gat=1; _ga=GA1.2.1032915092.1427933260"
so when you split on ; there will be an extra space before some of the key names.
function getcookie(cookiename){
var mycookies = []; // The cookie jar
var temp = document.cookie.split(";");
var key = "";
var val = "";
for(i=0;i<temp.length;i++){
key = temp[i].split("=")[0].trim(); // added trim here
val = temp[i].split("=")[1];
mycookies[key] = val;
}
return mycookies[cookiename];
}
Demo: JSBin
mycookies should be populated assuming temp.length is greater than 0. Your return value is always going to be undefined; mycookies[cookiename] is never assigned a value.
Try adding console.log(mycookies) just before your return statement.
Mycookies should be an Object, not an Array.
var mycookies = {};
JavaScript arrays are not associative arrays, only possible index values are numerical, starting with 0 and ending at array.length - 1. What you might have seen in examples before or used in another language before was JavaScript object, which does, in fact, behave as an associative array. You can access object values by object['key'] or as object.key. The first is used only when accessing key using a variable or a key which includes illegal characters, i.e. some-key, otherwise it's recommended to use dot access, as illustrated in second example.
Therefore your mycookies variable should be an object, not an array.
If you change your line var mycookies = []; to var mycookies = {};, i.e. change it from empty array to empty object, the remaining code should work as you expected.
Here is an example snippet for fixed code, I added a mock cookies string so it can work reliably:
var mockCookies = "a=1;b=2;c=3";
function getcookie(cookiename){
var mycookies = {}; // The cookie jar
var temp = mockCookies.split(";");
var key = "";
var val = "";
for(i=0;i<temp.length;i++){
key = temp[i].split("=")[0];
val = temp[i].split("=")[1];
mycookies[key] = val;
}
return mycookies[cookiename];
}
function printCookie(name) {
alert(getcookie(name));
}
<button onclick="printCookie('a')">Get a</button>
<button onclick="printCookie('b')">Get b</button>
<button onclick="printCookie('c')">Get c</button>
My friend, you are a little confused (maybe you have programmed in PHP) because in JavaScript, an Array is not a associative key : value object, it is an indexes based object. But what you looking for is an Object Literal
function getcookie (cookiename){
var i, max, keyvalue, key, val,
cookiesObj = {}, //empty object literal
cookiesArr = document.cookie.split(";");
for(i=0, max=cookiesArr.length; i<max; i+=1) {
keyvalue = cookiesArr[i].split("=");
key = keyvalue[0].trim();
val = keyvalue[1].trim();
cookiesObj[key] = val;
}
return cookiesObj[cookiename];
}
But you can refactor your code:
function getcookie (cookiename) {
var cookie = "",
cookies = document.cookie.split(";");
cookies.forEach(function (item) {
var keyvalue = item.split("="),
key = keyvalue[0].trim(),
val = keyvalue[1].trim();
if (key === cookiename) {
cookie = val;
return false; //exit from iteration
}
});
return cookie;
}

How to retrieve GET parameters from JavaScript [duplicate]

This question already has answers here:
How can I get query string values in JavaScript?
(73 answers)
Closed 5 years ago.
Consider:
http://example.com/page.html?returnurl=%2Fadmin
For js within page.html, how can it retrieve GET parameters?
For the above simple example, func('returnurl') should be /admin.
But it should also work for complex query strings...
With the window.location object. This code gives you GET without the question mark.
window.location.search.substr(1)
From your example it will return returnurl=%2Fadmin
EDIT: I took the liberty of changing Qwerty's answer, which is really good, and as he pointed I followed exactly what the OP asked:
function findGetParameter(parameterName) {
var result = null,
tmp = [];
location.search
.substr(1)
.split("&")
.forEach(function (item) {
tmp = item.split("=");
if (tmp[0] === parameterName) result = decodeURIComponent(tmp[1]);
});
return result;
}
I removed the duplicated function execution from his code, replacing it a variable ( tmp ) and also I've added decodeURIComponent, exactly as OP asked. I'm not sure if this may or may not be a security issue.
Or otherwise with plain for loop, which will work even in IE8:
function findGetParameter(parameterName) {
var result = null,
tmp = [];
var items = location.search.substr(1).split("&");
for (var index = 0; index < items.length; index++) {
tmp = items[index].split("=");
if (tmp[0] === parameterName) result = decodeURIComponent(tmp[1]);
}
return result;
}
window.location.search will return everything from the ? on. This code below will remove the ?, use split to separate into key/value arrays, then assign named properties to the params object:
function getSearchParameters() {
var prmstr = window.location.search.substr(1);
return prmstr != null && prmstr != "" ? transformToAssocArray(prmstr) : {};
}
function transformToAssocArray( prmstr ) {
var params = {};
var prmarr = prmstr.split("&");
for ( var i = 0; i < prmarr.length; i++) {
var tmparr = prmarr[i].split("=");
params[tmparr[0]] = tmparr[1];
}
return params;
}
var params = getSearchParameters();
You can then get the test parameter from http://myurl.com/?test=1 by calling params.test.
You should use URL and URLSearchParams native functions:
let url = new URL("https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8&q=mdn%20query%20string")
let params = new URLSearchParams(url.search);
let sourceid = params.get('sourceid') // 'chrome-instant'
let q = params.get('q') // 'mdn query string'
let ie = params.has('ie') // true
params.append('ping','pong')
console.log(sourceid)
console.log(q)
console.log(ie)
console.log(params.toString())
console.log(params.get("ping"))
https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
https://polyfill.io/v2/docs/features/
tl;dr solution on a single line of code using vanilla JavaScript
var queryDict = {}
location.search.substr(1).split("&").forEach(function(item) {queryDict[item.split("=")[0]] = item.split("=")[1]})
This is the simplest solution. It unfortunately does not handle multi-valued keys and encoded characters.
"?a=1&a=%2Fadmin&b=2&c=3&d&e"
> queryDict
a: "%2Fadmin" // Overridden with the last value, not decoded.
b: "2"
c: "3"
d: undefined
e: undefined
Multi-valued keys and encoded characters?
See the original answer at How can I get query string values in JavaScript?.
"?a=1&b=2&c=3&d&e&a=5&a=t%20e%20x%20t&e=http%3A%2F%2Fw3schools.com%2Fmy%20test.asp%3Fname%3Dståle%26car%3Dsaab&a=%2Fadmin"
> queryDict
a: ["1", "5", "t e x t", "/admin"]
b: ["2"]
c: ["3"]
d: [undefined]
e: [undefined, "http://w3schools.com/my test.asp?name=ståle&car=saab"]
In your example, you would access the value like this:
"?returnurl=%2Fadmin"
> qd.returnurl // ["/admin"]
> qd['returnurl'] // ["/admin"]
> qd.returnurl[0] // "/admin"
A more fancy way to do it: :)
var options = window.location.search.slice(1)
.split('&')
.reduce(function _reduce (/*Object*/ a, /*String*/ b) {
b = b.split('=');
a[b[0]] = decodeURIComponent(b[1]);
return a;
}, {});
This one uses a regular expression and returns null if the parameter doesn't exist or doesn't have any value:
function getQuery(q) {
return (window.location.search.match(new RegExp('[?&]' + q + '=([^&]+)')) || [, null])[1];
}
I do it like this (to retrieve a specific get-parameter, here 'parameterName'):
var parameterValue = decodeURIComponent(window.location.search.match(/(\?|&)parameterName\=([^&]*)/)[2]);
Here I've made this code to transform the GET parameters into an object to use them more easily.
// Get Nav URL
function getNavUrl() {
// Get URL
return window.location.search.replace("?", "");
};
function getParameters(url) {
// Params obj
var params = {};
// To lowercase
url = url.toLowerCase();
// To array
url = url.split('&');
// Iterate over URL parameters array
var length = url.length;
for(var i=0; i<length; i++) {
// Create prop
var prop = url[i].slice(0, url[i].search('='));
// Create Val
var value = url[i].slice(url[i].search('=')).replace('=', '');
// Params New Attr
params[prop] = value;
}
return params;
};
// Call of getParameters
console.log(getParameters(getNavUrl()));
I have created a simple JavaScript function to access GET parameters from URL.
Just include this JavaScript source and you can access get parameters.
E.g.: in http://example.com/index.php?language=french, the language variable can be accessed as $_GET["language"]. Similarly, a list of all parameters will be stored in a variable $_GET_Params as an array. Both the JavaScript and HTML are provided in the following code snippet:
<!DOCTYPE html>
<html>
<body>
<!-- This script is required -->
<script>
function $_GET() {
// Get the Full href of the page e.g. http://www.google.com/files/script.php?v=1.8.7&country=india
var href = window.location.href;
// Get the protocol e.g. http
var protocol = window.location.protocol + "//";
// Get the host name e.g. www.google.com
var hostname = window.location.hostname;
// Get the pathname e.g. /files/script.php
var pathname = window.location.pathname;
// Remove protocol part
var queries = href.replace(protocol, '');
// Remove host part
queries = queries.replace(hostname, '');
// Remove pathname part
queries = queries.replace(pathname, '');
// Presently, what is left in the variable queries is : ?v=1.8.7&country=india
// Perform query functions if present
if (queries != "" && queries != "?") {
// Remove question mark '?'
queries = queries.slice(1);
// Split all the different queries
queries = queries.split("&");
// Get the number of queries
var length = queries.length;
// Declare global variables to store keys and elements
$_GET_Params = new Array();
$_GET = {};
// Perform functions per query
for (var i = 0; i < length; i++) {
// Get the present query
var key = queries[i];
// Split the query and the value
key = key.split("=");
// Assign value to the $_GET variable
$_GET[key[0]] = [key[1]];
// Assign value to the $_GET_Params variable
$_GET_Params[i] = key[0];
}
}
}
// Execute the function
$_GET();
</script>
<h1>GET Parameters</h1>
<h2>Try to insert some get parameter and access it through JavaScript</h2>
</body>
</html>
var getQueryParam = function(param) {
var found;
window.location.search.substr(1).split("&").forEach(function(item) {
if (param == item.split("=")[0]) {
found = item.split("=")[1];
}
});
return found;
};
Here is another example based on Kat's and Bakudan's examples, but making it a just a bit more generic.
function getParams ()
{
var result = {};
var tmp = [];
location.search
.substr (1)
.split ("&")
.forEach (function (item)
{
tmp = item.split ("=");
result [tmp[0]] = decodeURIComponent (tmp[1]);
});
return result;
}
location.getParams = getParams;
console.log (location.getParams());
console.log (location.getParams()["returnurl"]);
To get the parameters as a JSON object:
console.log(getUrlParameters())
function getUrlParameters() {
var out = {};
var str = window.location.search.replace("?", "");
var subs = str.split(`&`).map((si)=>{var keyVal = si.split(`=`); out[keyVal[0]]=keyVal[1];});
return out
}
If you don't mind using a library instead of rolling your own implementation, check out https://github.com/jgallen23/querystring.
This solution handles URL decoding:
var params = function() {
function urldecode(str) {
return decodeURIComponent((str+'').replace(/\+/g, '%20'));
}
function transformToAssocArray( prmstr ) {
var params = {};
var prmarr = prmstr.split("&");
for ( var i = 0; i < prmarr.length; i++) {
var tmparr = prmarr[i].split("=");
params[tmparr[0]] = urldecode(tmparr[1]);
}
return params;
}
var prmstr = window.location.search.substr(1);
return prmstr != null && prmstr != "" ? transformToAssocArray(prmstr) : {};
}();
Usage:
console.log('someParam GET value is', params['someParam']);
My solution expands on #tak3r's.
It returns an empty object when there are no query parameters and supports the array notation ?a=1&a=2&a=3:
function getQueryParams () {
function identity (e) { return e; }
function toKeyValue (params, param) {
var keyValue = param.split('=');
var key = keyValue[0], value = keyValue[1];
params[key] = params[key]?[value].concat(params[key]):value;
return params;
}
return decodeURIComponent(window.location.search).
replace(/^\?/, '').split('&').
filter(identity).
reduce(toKeyValue, {});
}
You can use the search function available in the location object. The search function gives the parameter part of the URL. Details can be found in Location Object.
You will have to parse the resulting string for getting the variables and their values, e.g. splitting them on '='.
If you are using AngularJS, you can use $routeParams using ngRoute module
You have to add a module to your app
angular.module('myApp', ['ngRoute'])
Now you can use service $routeParams:
.controller('AppCtrl', function($routeParams) {
console.log($routeParams); // JSON object
}

JavaScript query string [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 6 years ago.
Improve this question
Is there any JavaScript library that makes a dictionary out of the query string, ASP.NET style?
Something which can be used like:
var query = window.location.querystring["query"]?
Is "query string" called something else outside the .NET realm? Why isn't location.search broken into a key/value collection ?
EDIT: I have written my own function, but does any major JavaScript library do this?
You can extract the key/value pairs from the location.search property, this property has the part of the URL that follows the ? symbol, including the ? symbol.
function getQueryString() {
var result = {}, queryString = location.search.slice(1),
re = /([^&=]+)=([^&]*)/g, m;
while (m = re.exec(queryString)) {
result[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
}
return result;
}
// ...
var myParam = getQueryString()["myParam"];
tl;dr solution on a single(ish) line of code using vanilla javascript
var queryDict = {}
location.search.substr(1).split("&").forEach(function(item) {
queryDict[item.split("=")[0]] = item.split("=")[1]
})
For querystring ?a=1&b=2&c=3&d&eit returns:
> queryDict
a: "1"
b: "2"
c: "3"
d: undefined
e: undefined
multi-valued keys and encoded characters?
See the original answer at How can I get query string values in JavaScript?
"?a=1&b=2&c=3&d&e&a=5&a=t%20e%20x%20t&e=http%3A%2F%2Fw3schools.com%2Fmy%20test.asp%3Fname%3Dståle%26car%3Dsaab"
> queryDict
a: ["1", "5", "t e x t"]
b: ["2"]
c: ["3"]
d: [undefined]
e: [undefined, "http://w3schools.com/my test.asp?name=ståle&car=saab"]
Maybe http://plugins.jquery.com/query-object/?
This is the fork of it https://github.com/sousk/jquery.parsequery#readme.
After finding this post, when looking myself I thought I should add that I don't think the most up-voted solution is the best. It doesn't handle array values (such as ?a=foo&a=bar - in this case I would expect getting a to return ['foo', 'bar']). It also as far as I can tell doesn't take into account encoded values - such as hex character encoding where %20 represents a space (example: ?a=Hello%20World) or the plus symbol being used to represent a space (example: ?a=Hello+World).
Node.js offers what looks like a very complete solutions to querystring parsing. It would be easy to take out and use in your own project as its fairly well isolated and under a permissive licence.
The code for it can be viewed here: https://github.com/joyent/node/blob/master/lib/querystring.js
The tests that Node has can be seen here:
https://github.com/joyent/node/blob/master/test/simple/test-querystring.js I would suggest trying some of these with the popular answer to see how it handles them.
There is also a project that I was involved in to specifically add this functionality. It is a port of the Python standard lib query string parsing module. My fork can be found here: https://github.com/d0ugal/jquery.qeeree
Or you could use the library sugar.js.
From sugarjs.com:
Object.fromQueryString ( str , deep = true )
Converts the query string of a URL into an object. If deep is false,
conversion will only accept shallow params (ie. no object or arrays
with [] syntax) as these are not universally supported.
Object.fromQueryString('foo=bar&broken=wear') >{"foo":"bar","broken":"wear"}
Object.fromQueryString('foo[]=1&foo[]=2') >{"foo":[1,2]}
Example:
var queryString = Object.fromQueryString(location.search);
var foo = queryString.foo;
If you have the querystring on hand, use this:
/**
* #param qry the querystring
* #param name name of parameter
* #returns the parameter specified by name
* #author eduardo.medeirospereira#gmail.com
*/
function getQueryStringParameter(qry,name){
if(typeof qry !== undefined && qry !== ""){
var keyValueArray = qry.split("&");
for ( var i = 0; i < keyValueArray.length; i++) {
if(keyValueArray[i].indexOf(name)>-1){
return keyValueArray[i].split("=")[1];
}
}
}
return "";
}
// How about this
function queryString(qs) {
var queryStr = qs.substr(1).split("&"),obj={};
for(var i=0; i < queryStr.length;i++)
obj[queryStr[i].split("=")[0]] = queryStr[i].split("=")[1];
return obj;
}
// Usage:
var result = queryString(location.search);
It is worth noting, the library that John Slegers mentioned does have a jQuery dependency, however here is a version that is vanilla Javascript.
https://github.com/EldonMcGuinness/querystring.js
I would have simply commented on his post, but I lack the reputation to do so. :/
Example:
The example below process the following, albeit irregular, query string:
?foo=bar&foo=boo&roo=bar;bee=bop;=ghost;=ghost2;&;checkbox%5B%5D=b1;checkbox%5B%5D=b2;dd=;http=http%3A%2F%2Fw3schools.com%2Fmy%20test.asp%3Fname%3Dst%C3%A5le%26car%3Dsaab&http=http%3A%2F%2Fw3schools2.com%2Fmy%20test.asp%3Fname%3Dst%C3%A5le%26car%3Dsaab
var qs = "?foo=bar&foo=boo&roo=bar;bee=bop;=ghost;=ghost2;&;checkbox%5B%5D=b1;checkbox%5B%5D=b2;dd=;http=http%3A%2F%2Fw3schools.com%2Fmy%20test.asp%3Fname%3Dst%C3%A5le%26car%3Dsaab&http=http%3A%2F%2Fw3schools2.com%2Fmy%20test.asp%3Fname%3Dst%C3%A5le%26car%3Dsaab";
//var qs = "?=&=";
//var qs = ""
var results = querystring(qs);
(document.getElementById("results")).innerHTML =JSON.stringify(results, null, 2);
<script
src="https://rawgit.com/EldonMcGuinness/querystring.js/master/dist/querystring.min.js"></script>
<pre id="results">RESULTS: Waiting...</pre>
The code
This Gist by Eldon McGuinness is by far the most complete implementation of a JavaScript query string parser that I've seen so far.
Unfortunately, it's written as a jQuery plugin.
I rewrote it to vanilla JS and made a few improvements :
function parseQuery(str) {
var qso = {};
var qs = (str || document.location.search);
// Check for an empty querystring
if (qs == "") {
return qso;
}
// Normalize the querystring
qs = qs.replace(/(^\?)/, '').replace(/;/g, '&');
while (qs.indexOf("&&") != -1) {
qs = qs.replace(/&&/g, '&');
}
qs = qs.replace(/([\&]+$)/, '');
// Break the querystring into parts
qs = qs.split("&");
// Build the querystring object
for (var i = 0; i < qs.length; i++) {
var qi = qs[i].split("=");
qi = qi.map(function(n) {
return decodeURIComponent(n)
});
if (typeof qi[1] === "undefined") {
qi[1] = null;
}
if (typeof qso[qi[0]] !== "undefined") {
// If a key already exists then make this an object
if (typeof (qso[qi[0]]) == "string") {
var temp = qso[qi[0]];
if (qi[1] == "") {
qi[1] = null;
}
qso[qi[0]] = [];
qso[qi[0]].push(temp);
qso[qi[0]].push(qi[1]);
} else if (typeof (qso[qi[0]]) == "object") {
if (qi[1] == "") {
qi[1] = null;
}
qso[qi[0]].push(qi[1]);
}
} else {
// If no key exists just set it as a string
if (qi[1] == "") {
qi[1] = null;
}
qso[qi[0]] = qi[1];
}
}
return qso;
}
How to use it
var results = parseQuery("?foo=bar&foo=boo&roo=bar;bee=bop;=ghost;=ghost2;&;checkbox%5B%5D=b1;checkbox%5B%5D=b2;dd=;http=http%3A%2F%2Fw3schools.com%2Fmy%20test.asp%3Fname%3Dst%C3%A5le%26car%3Dsaab&http=http%3A%2F%2Fw3schools2.com%2Fmy%20test.asp%3Fname%3Dst%C3%A5le%26car%3Dsaab");
Output
{
"foo": ["bar", "boo" ],
"roo": "bar",
"bee": "bop",
"": ["ghost", "ghost2"],
"checkbox[]": ["b1", "b2"],
"dd": null,
"http": [
"http://w3schools.com/my test.asp?name=ståle&car=saab",
"http://w3schools2.com/my test.asp?name=ståle&car=saab"
]
}
See also this Fiddle.
function decode(s) {
try {
return decodeURIComponent(s).replace(/\r\n|\r|\n/g, "\r\n");
} catch (e) {
return "";
}
}
function getQueryString(win) {
var qs = win.location.search;
var multimap = {};
if (qs.length > 1) {
qs = qs.substr(1);
qs.replace(/([^=&]+)=([^&]*)/g, function(match, hfname, hfvalue) {
var name = decode(hfname);
var value = decode(hfvalue);
if (name.length > 0) {
if (!multimap.hasOwnProperty(name)) {
multimap[name] = [];
}
multimap[name].push(value);
}
});
}
return multimap;
}
var keys = getQueryString(window);
for (var i in keys) {
if (keys.hasOwnProperty(i)) {
for (var z = 0; z < keys[i].length; ++z) {
alert(i + ":" + keys[i][z]);
}
}
}
I like to keep it simple, readable and small.
function searchToObject(search) {
var pairs = search.substring(1).split("&"),
obj = {}, pair;
for (var i in pairs) {
if (pairs[i] === "") continue;
pair = pairs[i].split("=");
obj[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
}
return obj;
}
searchToObject(location.search);
Example:
searchToObject('?query=myvalue')['query']; // spits out: 'myvalue'
Function I wrote for a requirement similar to this with pure javascript string manipulation
"http://www.google.lk/?Name=John&Age=20&Gender=Male"
function queryize(sampleurl){
var tokens = url.split('?')[1].split('&');
var result = {};
for(var i=0; i<tokens.length; i++){
result[tokens[i].split('=')[0]] = tokens[i].split('=')[1];
}
return result;
}
Usage:
queryize(window.location.href)['Name'] //returns John
queryize(window.location.href)['Age'] //returns 20
queryize(window.location.href)['Gender'] //returns Male
If you are using lodash + ES6, here is a one line solution:
_.object(window.location.search.replace(/(^\?)/, '').split('&').map(keyVal => keyVal.split('=')));
Okay, since everyone is ignoring my actual question, heh, I'll post mine too! Here's what I have:
location.querystring = (function() {
// The return is a collection of key/value pairs
var queryStringDictionary = {};
// Gets the query string, starts with '?'
var querystring = unescape(location.search);
// document.location.search is empty if no query string
if (!querystring) {
return {};
}
// Remove the '?' via substring(1)
querystring = querystring.substring(1);
// '&' seperates key/value pairs
var pairs = querystring.split("&");
// Load the key/values of the return collection
for (var i = 0; i < pairs.length; i++) {
var keyValuePair = pairs[i].split("=");
queryStringDictionary[keyValuePair[0]] = keyValuePair[1];
}
// Return the key/value pairs concatenated
queryStringDictionary.toString = function() {
if (queryStringDictionary.length == 0) {
return "";
}
var toString = "?";
for (var key in queryStringDictionary) {
toString += key + "=" + queryStringDictionary[key];
}
return toString;
};
// Return the key/value dictionary
return queryStringDictionary;
})();
And the tests:
alert(window.location.querystring.toString());
for (var key in location.querystring) {
alert(key + "=" + location.querystring[key]);
}
Mind you thought, JavaScript isn't my native tongue.
Anyway, I'm looking for a JavaScript library (e.g. jQuery, Prototype) that already has one written. :)
Building on the answer by #CMS I have the following (in CoffeeScript which can easily be converted to JavaScript):
String::to_query = ->
[result, re, d] = [{}, /([^&=]+)=([^&]*)/g, decodeURIComponent]
while match = re.exec(if #.match /^\?/ then #.substring(1) else #)
result[d(match[1])] = d match[2]
result
You can easily grab what you need with:
location.search.to_query()['my_param']
The win here is an object-oriented interface (instead of functional) and it can be done on any string (not just location.search).
If you are already using a JavaScript library this function make already exist. For example here is Prototype's version

Categories

Resources