Get Query String Values for Duplicate GET Variables - javascript

I've seen how to parse query string info (GET variables) using Javascript and jQuery. There are two different examples here (I've always preferred the second one):
How can I get query string values in JavaScript?
jquery get querystring from URL
The problem is that I have a query string that has two of the same GET variables (they are both called 'search'). When I run the function from the first answer, it only returns the first instance of the 'search' GET variable and the second answer only returns the last 'search' GET variable. An example query string would be:
http://www.example.com?search=this&search=that
I did some searching and there's an answer in this thread that seems to deal with the issue:
https://gist.github.com/kares/956897
But I don't know exactly how to implement it with the way it's written. I basically am looking for a function that can parse the query string and return all (if any) values of that match the particular GET variable (in this case 'search'; in the above example it would return 'this' and 'that').
Thanks for your help!

This should do the trick:
var params = location.search.substr(1).split('&'),
results = {};
for(var i = 0; i < params.length; i++)
{
var temp = params[i].split('='),
key = temp[0],
val = temp[1];
results[key] = results[key] || [];
results[key].push(val);
}
console.log(results); // { search: ["a", "b"] }

// Read a page's GET URL variables and return them as an associative array.
function getUrlVars()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
if(typeof vars[hash[0]]=='undefined'){
vars.push(hash[0]);
vars[hash[0]] = [hash[1]];
}else{
vars[hash[0]].push(hash[1]);
}
}
return vars;
}
You can find demo here

Related

Reduce javascript object to unique identifier

I have an object that I'm storing page settings in that looks something like this:
var filters={
"brands":["brand1","brand2","brand3"],
"family":"reds",
"palettes":["palette1","palette2","palette3"],
"color":"a1b2"
};
This object is constantly being changed as the user browses the page. I looking for some fast way in the code (maybe using a built in jquery or javascript function) to reduce the current settings object to a unique identifier I can reference without using a lot of loops. Maybe something like this:
"brandsbrand1brand2brand3familyredspalettespalette1palette2palette3colora1b2"
Doesn't have to necessarily convert the object to a long string like that, as long as it is something that will be unique to a particular group of settings. And I won't need to convert this identifier back into the object later.
EDITS:
I need to give some more information.
I'm looking to store the items of the results of the filters I'm doing inside a variable that's named the same as the unique ID. So, var uniqueID1 is from the settings object that has brand1 and brand2, and contains ["filteredObject1_1","filteredObject1_2"...,"filteredObject1_500"], and var uniqueID2 is from the settings object that has brand3 and brand4, and contains ["filteredObject2_1","filteredObject2_2"...,"filteredObject2_500"]. What I'm looking to do is avoid doing really really slow filtering code more than once on a bunch of items by storing results of the filtering in unique variables.
So:
Convert settings to unique id and see if that if that variable exists.
If variable exists, just get that variable that has the already filtered items.
If variable doesn't exist, do the really slow filtering on hundreds of items and store these items in unique id variable.
Hopefully I just didn't make this more confusing. I feel like I probably made it more confusing.
You can use JSON, which is a method of stringifying objects that was designed for JavaScript.
var filters={
"brands":["brand1","brand2","brand3"],
"family":"reds",
"palettes":["palette1","palette2","palette3"],
"color":"a1b2"
};
var uniqueId = JSON.stringify(filters);
uniqueId equals the following string:
{"brands":["brand1","brand2","brand3"],"family":"reds","palettes":["palette1","palette2","palette3"],"color":"a1b2"}
This has the added benefit of being able to be turned back into an object with JSON.parse(uniqueId).
Note that with JSON.stringify, two objects with have exactly the same values will be converted into the same unique id.
EDIT:
Please let me know if I interpreted your edit correctly. However, I think this is what you want to do.
//object that will act as a cache
var cached_filters = {}
//this assumes the existence of a get_filter function that processes the filters object
function get_cached_filter(filters) {
let uniqueId = JSON.stringify(filters);
//use already cached filters
if (cached_filters[uniqueId]) {
return cached_filters[uniqueId];
//create filter and cache it
} else {
cached_filters[uniqueId] = get_filter(filters);
return cached_filters[uniqueId];
}
}
This will store an object that has keys for each filter each time you call get_cached_filter. If get_cached_filter has already been called with the same exact filter, it will use it from the cache instead of recreating it; otherwise, it will create it and save it in the cache.
You could iterate the filter object and filter with Array#filter the data.
data.filter(function (o) {
return Object.keys(filters).every(function (k) {
return Array.isArray(filters[k])
? filters[k].some(function (f) { return o[k] === f; })
: o[k] === filters[k];
});
});
If you won't need to convert this identifier back into the object later, Here you can use this simple hashing function:
function UniqueHashCode(obj){
var str = JSON.stringify(obj)
var hash = 0;
if (str.length == 0) return hash;
for (i = 0; i < str.length; i++) {
char = str.charCodeAt(i);
hash = ((hash<<5)-hash)+char;
hash = hash & hash; // Convert to 32bit integer
}
return hash;
}
function UniqueHashCode(obj){
var str = JSON.stringify(obj)
var hash = 0;
if (str.length == 0) return hash;
for (i = 0; i < str.length; i++) {
char = str.charCodeAt(i);
hash = ((hash<<5)-hash)+char;
hash = hash & hash; // Convert to 32bit integer
}
return hash;
}
var filters={
"brands":["brand1","brand2","brand3"],
"family":"reds",
"palettes":["palette1","palette2","palette3"],
"color":"a1b2"
};
alert(UniqueHashCode(filters));
This function create a simple and very short integer (for example 661801383) by given object.
I hope to be helpful for you:)

How do I parse variables from URL in 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
}

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"] }.

why am I getting "object Object" when I call .toString on a JS array?

I'm trying to look at all the cookies in a given document with this:
function get_cookies_array() {
var cookies = {};
if (document.cookie && document.cookie != '') {
var split = document.cookie.split(';');
for (var i = 0; i < split.length; i++) {
var name_value = split[i].split("=");
name_value[0] = name_value[0].replace(/^ /, '');
cookies[decodeURIComponent(name_value[0])] = decodeURIComponent(name_value[1]);
}
}
return cookies;
}
var cookies = get_cookies_array();
alert(cookies.toString());
However, what i'm seeing in the alert box is
[object Object]
I was expecting a comma separated list of values. What am I doing wrong?
The value being returned is not an array. It's a plain object. Presumably you do want to use an object here, so that you can use string-valued keys. You can print out its contents like so:
var cookies = get_cookies_array();
console.log(JSON.stringify(cookies));
Or line by line:
Object.keys(cookies).forEach(function (key) {
console.log(key, ' - ', cookies[key]);
});
Replace var cookies = {}; with var cookies = []; so that you are dealing with an Array instead of an Object.
Then, because you are using an associative array, also change your writing into array like this:
cookies.push([decodeURIComponent(name_value[0]), decodeURIComponent(name_value[1])]);

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
}

Categories

Resources