Get Url string parameter as JSON object - javascript

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);

Related

str.split to json with names

I have taken a string that is "title:artist" and used str.split :
res = song.split(":");
Which gives me an output of :
["Ruby","Kaiser Chiefs"]
I was wondering how I could add name to this so that it appears as :
["name":"Ruby", "artist":"Kaiser Chiefs"]
var res = song.split(':');
var jsonString = JSON.stringify({ name: res[0], artist: res[1] });
You can find more information about how to use JSON.stringify here but basically what it does is takes a JavaScript object (see how I'm passing the data as an object in my answer) and serializes it into a JSON string.
Be aware that the output is not exactly as you have described in your question. What you have is both invalid JavaScript and invalid JSON. The output that I have provided will look more along the lines of {"name":"Ruby", "artist":"Kaiser Chiefs"}. Notice how there is {} instead of [].
["name":"Ruby", "artist":"Kaiser Chiefs"] isn't a valid format I guess you want to create an object so you could use just the split like :
var my_string = "Ruby:Kaiser Chiefs";
var my_string_arr = my_string.split(':');
var my_object = {'name': my_string_arr[0],"artist": my_string_arr[1]};
console.log(my_object);
Or also assign the values to the attributes separately like:
var my_string = "Ruby:Kaiser Chiefs";
var my_string_arr = my_string.split(':');
var my_object = {};
my_object.name = my_string_arr[0];
my_object.artist = my_string_arr[1];
console.log(my_object);
Hope this helps.
What you're looking for is: Object. Here is how you do it:
var str = "Ruby:Kaiser Chiefs";
var res = str.split(':');
// this is how to declare an object
var myObj = {};
// this is one way to assigne to an object
// using: myObj["key"] = value;
myObj["name"] = res[0];
// this is another way to assign to an object
// using: myObj.key = value;
myObj.artist = res[1];
console.log(myObj);

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
}

How to access first element of JSON object array?

I exptect that mandrill_events only contains one object. How do I access its event-property?
var req = { mandrill_events: '[{"event":"inbound","ts":1426249238}]' }
var req = { mandrill_events: '[{"event":"inbound","ts":1426249238}]' }
console.log(Object.keys(req)[0]);
Make any Object array (req), then simply do Object.keys(req)[0] to pick the first key in the Object array.
To answer your titular question, you use [0] to access the first element, but as it stands mandrill_events contains a string not an array, so mandrill_events[0] will just get you the first character, '['.
So either correct your source to:
var req = { mandrill_events: [{"event":"inbound","ts":1426249238}] };
and then req.mandrill_events[0], or if you're stuck with it being a string, parse the JSON the string contains:
var req = { mandrill_events: '[{"event":"inbound","ts":1426249238}]' };
var mandrill_events = JSON.parse(req.mandrill_events);
var result = mandrill_events[0];
the event property seems to be string first you have to parse it to json :
var req = { mandrill_events: '[{"event":"inbound","ts":1426249238}]' };
var event = JSON.parse(req.mandrill_events);
var ts = event[0].ts
I'll explain this with a general example:
var obj = { name: "John", age: 30, city: "New York" };
var result = obj[Object.keys(obj)[0]];
The result variable will have the value "John"
'[{"event":"inbound","ts":1426249238}]' is a string, you cannot access any properties there. You will have to parse it to an object, with JSON.parse() and then handle it like a normal object
After you parse it with Javascript, try this:
mandrill_events[0].event
Assuming thant the content of mandrill_events is an object (not a string), you can also use shift() function:
var req = { mandrill_events: [{"event":"inbound","ts":1426249238}] };
var event-property = req.mandrill_events.shift().event;

javascript object to string

I'm trying to serialize a javascript object but with a particular form(I think it has to be a method).
Example:
var media = new Object();
media.url = "localhost";
media.foo = "asd"
var data=new Object();
data.title = "myTitle";
data.description = "myDescription";
data.media.push(media);
I need to serialize data this way:
"title=myTitle&description=myDescription&media[0].url=localhost&media[0].foo=asd"
The important thing is the way the array is written.
Check out Convert a JSON object's keys into dot notation paths and Convert complex JavaScript object to dot notation object. You can easily adapt those to handle your array keys special:
function transform(obj) {
var result = {};
recurse(obj, "");
return result;
function recurse(o, name) {
if (Object(o) !== o)
result[name] = o;
else if (Array.isArray(o))
for (var i=0; i<o.length; i++)
recurse(o[i], name+"["+i+"]");
else // if plain object?
for (var p in o)
recurse(o[p], name?name+"."+p:p);
}
}
You can then apply $.param on the result to get the URL encoding etc:
$.param(transform(data))
(or just pass it into the data parameter of $.ajax).
There are multiple ways to serialize an object into a list (string) of parameters, have a look:
How to serialize an Object into a list of parameters?
One example is a method such as the below:
var str = "";
for (var key in obj) {
if (str != "") {
str += "&";
}
str += key + "=" + obj[key];
}
You can modify it to suit the style you need.
jQuery provides this via jQuery.param
var params = $.param(data);
console.log(params);
Produces:
title=myTitle&description=myDescription&media%5B0%5D%5Burl%5D=localhost&media%5B0%5D%5Bfoo%5D=asd
As you can see, it handles the nested array and object as you wish (%5B and %5D are URL encodings for [ and ]).
If you're using $.ajax() or one of its shortcuts, you don't need to call this explicitly. If you supply the object as the data argument or option, jQuery will automatically serialize it using this method.
you can use jQuery.param to do this:
$.param({a:'2', b: 1.2, c: "hello world"})// -> a=2&b=1.2&c=hello+world
EDIT
What I was missing above is the array support sorry bout that.
For this you'll need to decodeURIComponent()
var media = new Object();
media.url = "localhost";
media.foo = "asd"
var data=new Object();
data.title = "myTitle";
data.description = "myDescription";
data.media = [];
data.media.push(media);
alert(decodeURIComponent($.param(data)));
Output:
title=myTitle&description=myDescription&media[0][url]=localhost&media[0][foo]=asd
http://jsfiddle.net/bLu8Q/
Sorry, but I need to change. Thought it was easier but when looking at the result I saw that it was not so straight forward. If you're using jquery though you can simply do it like this:
var media = new Object();
media.url = "localhost";
media.foo = "asd"
var data=new Object();
data.title = "myTitle";
data.description = "myDescription";
data.media = []; // you forgot this...
data.media.push(media);
var data = $.param(data));

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