JavaScript query string [closed] - javascript

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

Related

JavaScript: Access object field that has dot as key [duplicate]

Given a JavaScript object,
var obj = { a: { b: '1', c: '2' } }
and a string
"a.b"
how can I convert the string to dot notation so I can go
var val = obj.a.b
If the string was just 'a', I could use obj[a]. But this is more complex. I imagine there is some straightforward method, but it escapes me at present.
recent note: While I'm flattered that this answer has gotten many upvotes, I am also somewhat horrified. If one needs to convert dot-notation strings like "x.a.b.c" into references, it could (maybe) be a sign that there is something very wrong going on (unless maybe you're performing some strange deserialization).
That is to say, novices who find their way to this answer must ask themselves the question "why am I doing this?"
It is of course generally fine to do this if your use case is small and you will not run into performance issues, AND you won't need to build upon your abstraction to make it more complicated later. In fact, if this will reduce code complexity and keep things simple, you should probably go ahead and do what OP is asking for. However, if that's not the case, consider if any of these apply:
case 1: As the primary method of working with your data (e.g. as your app's default form of passing objects around and dereferencing them). Like asking "how can I look up a function or variable name from a string".
This is bad programming practice (unnecessary metaprogramming specifically, and kind of violates function side-effect-free coding style, and will have performance hits). Novices who find themselves in this case, should instead consider working with array representations, e.g. ['x','a','b','c'], or even something more direct/simple/straightforward if possible: like not losing track of the references themselves in the first place (most ideal if it's only client-side or only server-side), etc. (A pre-existing unique id would be inelegant to add, but could be used if the spec otherwise requires its existence regardless.)
case 2: Working with serialized data, or data that will be displayed to the user. Like using a date as a string "1999-12-30" rather than a Date object (which can cause timezone bugs or added serialization complexity if not careful). Or you know what you're doing.
This is maybe fine. Be careful that there are no dot strings "." in your sanitized input fragments.
If you find yourself using this answer all the time and converting back and forth between string and array, you may be in the bad case, and should consider an alternative.
Here's an elegant one-liner that's 10x shorter than the other solutions:
function index(obj,i) {return obj[i]}
'a.b.etc'.split('.').reduce(index, obj)
[edit] Or in ECMAScript 6:
'a.b.etc'.split('.').reduce((o,i)=> o[i], obj)
(Not that I think eval always bad like others suggest it is (though it usually is), nevertheless those people will be pleased that this method doesn't use eval. The above will find obj.a.b.etc given obj and the string "a.b.etc".)
In response to those who still are afraid of using reduce despite it being in the ECMA-262 standard (5th edition), here is a two-line recursive implementation:
function multiIndex(obj,is) { // obj,['1','2','3'] -> ((obj['1'])['2'])['3']
return is.length ? multiIndex(obj[is[0]],is.slice(1)) : obj
}
function pathIndex(obj,is) { // obj,'1.2.3' -> multiIndex(obj,['1','2','3'])
return multiIndex(obj,is.split('.'))
}
pathIndex('a.b.etc')
Depending on the optimizations the JS compiler is doing, you may want to make sure any nested functions are not re-defined on every call via the usual methods (placing them in a closure, object, or global namespace).
edit:
To answer an interesting question in the comments:
how would you turn this into a setter as well? Not only returning the values by path, but also setting them if a new value is sent into the function? – Swader Jun 28 at 21:42
(sidenote: sadly can't return an object with a Setter, as that would violate the calling convention; commenter seems to instead be referring to a general setter-style function with side-effects like index(obj,"a.b.etc", value) doing obj.a.b.etc = value.)
The reduce style is not really suitable to that, but we can modify the recursive implementation:
function index(obj,is, value) {
if (typeof is == 'string')
return index(obj,is.split('.'), value);
else if (is.length==1 && value!==undefined)
return obj[is[0]] = value;
else if (is.length==0)
return obj;
else
return index(obj[is[0]],is.slice(1), value);
}
Demo:
> obj = {a:{b:{etc:5}}}
> index(obj,'a.b.etc')
5
> index(obj,['a','b','etc']) #works with both strings and lists
5
> index(obj,'a.b.etc', 123) #setter-mode - third argument (possibly poor form)
123
> index(obj,'a.b.etc')
123
...though personally I'd recommend making a separate function setIndex(...). I would like to end on a side-note that the original poser of the question could (should?) be working with arrays of indices (which they can get from .split), rather than strings; though there's usually nothing wrong with a convenience function.
A commenter asked:
what about arrays? something like "a.b[4].c.d[1][2][3]" ? –AlexS
Javascript is a very weird language; in general objects can only have strings as their property keys, so for example if x was a generic object like x={}, then x[1] would become x["1"]... you read that right... yup...
Javascript Arrays (which are themselves instances of Object) specifically encourage integer keys, even though you could do something like x=[]; x["puppy"]=5;.
But in general (and there are exceptions), x["somestring"]===x.somestring (when it's allowed; you can't do x.123).
(Keep in mind that whatever JS compiler you're using might choose, maybe, to compile these down to saner representations if it can prove it would not violate the spec.)
So the answer to your question would depend on whether you're assuming those objects only accept integers (due to a restriction in your problem domain), or not. Let's assume not. Then a valid expression is a concatenation of a base identifier plus some .identifiers plus some ["stringindex"]s.
Let us ignore for a moment that we can of course do other things legitimately in the grammar like identifier[0xFA7C25DD].asdf[f(4)?.[5]+k][false][null][undefined][NaN]; integers are not (that) 'special'.
Commenter's statement would then be equivalent to a["b"][4]["c"]["d"][1][2][3], though we should probably also support a.b["c\"validjsstringliteral"][3]. You'd have to check the ecmascript grammar section on string literals to see how to parse a valid string literal. Technically you'd also want to check (unlike in my first answer) that a is a valid javascript identifier.
A simple answer to your question though, if your strings don't contain commas or brackets, would be just be to match length 1+ sequences of characters not in the set , or [ or ]:
> "abc[4].c.def[1][2][\"gh\"]".match(/[^\]\[.]+/g)
// ^^^ ^ ^ ^^^ ^ ^ ^^^^^
["abc", "4", "c", "def", "1", "2", ""gh""]
If your strings don't contain escape characters or " characters, and because IdentifierNames are a sublanguage of StringLiterals (I think???) you could first convert your dots to []:
> var R=[], demoString="abc[4].c.def[1][2][\"gh\"]";
> for(var match,matcher=/^([^\.\[]+)|\.([^\.\[]+)|\["([^"]+)"\]|\[(\d+)\]/g;
match=matcher.exec(demoString); ) {
R.push(Array.from(match).slice(1).filter(x=> x!==undefined)[0]);
// extremely bad code because js regexes are weird, don't use this
}
> R
["abc", "4", "c", "def", "1", "2", "gh"]
Of course, always be careful and never trust your data. Some bad ways to do this that might work for some use cases also include:
// hackish/wrongish; preprocess your string into "a.b.4.c.d.1.2.3", e.g.:
> yourstring.replace(/]/g,"").replace(/\[/g,".").split(".")
"a.b.4.c.d.1.2.3" //use code from before
Special 2018 edit:
Let's go full-circle and do the most inefficient, horribly-overmetaprogrammed solution we can come up with... in the interest of syntactical purityhamfistery. With ES6 Proxy objects!... Let's also define some properties which (imho are fine and wonderful but) may break improperly-written libraries. You should perhaps be wary of using this if you care about performance, sanity (yours or others'), your job, etc.
// [1,2,3][-1]==3 (or just use .slice(-1)[0])
if (![1][-1])
Object.defineProperty(Array.prototype, -1, {get() {return this[this.length-1]}}); //credit to caub
// WARNING: THIS XTREME™ RADICAL METHOD IS VERY INEFFICIENT,
// ESPECIALLY IF INDEXING INTO MULTIPLE OBJECTS,
// because you are constantly creating wrapper objects on-the-fly and,
// even worse, going through Proxy i.e. runtime ~reflection, which prevents
// compiler optimization
// Proxy handler to override obj[*]/obj.* and obj[*]=...
var hyperIndexProxyHandler = {
get: function(obj,key, proxy) {
return key.split('.').reduce((o,i)=> o[i], obj);
},
set: function(obj,key,value, proxy) {
var keys = key.split('.');
var beforeLast = keys.slice(0,-1).reduce((o,i)=> o[i], obj);
beforeLast[keys[-1]] = value;
},
has: function(obj,key) {
//etc
}
};
function hyperIndexOf(target) {
return new Proxy(target, hyperIndexProxyHandler);
}
Demo:
var obj = {a:{b:{c:1, d:2}}};
console.log("obj is:", JSON.stringify(obj));
var objHyper = hyperIndexOf(obj);
console.log("(proxy override get) objHyper['a.b.c'] is:", objHyper['a.b.c']);
objHyper['a.b.c'] = 3;
console.log("(proxy override set) objHyper['a.b.c']=3, now obj is:", JSON.stringify(obj));
console.log("(behind the scenes) objHyper is:", objHyper);
if (!({}).H)
Object.defineProperties(Object.prototype, {
H: {
get: function() {
return hyperIndexOf(this); // TODO:cache as a non-enumerable property for efficiency?
}
}
});
console.log("(shortcut) obj.H['a.b.c']=4");
obj.H['a.b.c'] = 4;
console.log("(shortcut) obj.H['a.b.c'] is obj['a']['b']['c'] is", obj.H['a.b.c']);
Output:
obj is: {"a":{"b":{"c":1,"d":2}}}
(proxy override get) objHyper['a.b.c'] is: 1
(proxy override set) objHyper['a.b.c']=3, now obj is: {"a":{"b":{"c":3,"d":2}}}
(behind the scenes) objHyper is: Proxy {a: {…}}
(shortcut) obj.H['a.b.c']=4
(shortcut) obj.H['a.b.c'] is obj['a']['b']['c'] is: 4
inefficient idea: You can modify the above to dispatch based on the input argument; either use the .match(/[^\]\[.]+/g) method to support obj['keys'].like[3]['this'], or if instanceof Array, then just accept an Array as input like keys = ['a','b','c']; obj.H[keys].
Per suggestion that maybe you want to handle undefined indices in a 'softer' NaN-style manner (e.g. index({a:{b:{c:...}}}, 'a.x.c') return undefined rather than uncaught TypeError)...:
This makes sense from the perspective of "we should return undefined rather than throw an error" in the 1-dimensional index situation ({})['e.g.']==undefined, so "we should return undefined rather than throw an error" in the N-dimensional situation.
This does not make sense from the perspective that we are doing x['a']['x']['c'], which would fail with a TypeError in the above example.
That said, you'd make this work by replacing your reducing function with either:
(o,i)=> o===undefined?undefined:o[i], or
(o,i)=> (o||{})[i].
(You can make this more efficient by using a for loop and breaking/returning whenever the subresult you'd next index into is undefined, or using a try-catch if you expect such failures to be sufficiently rare.)
If you can use Lodash, there is a function, which does exactly that:
_.get(object, path, [defaultValue])
var val = _.get(obj, "a.b");
You could use lodash.get
After installing (npm i lodash.get), use it like this:
const get = require('lodash.get');
const myObj = {
user: {
firstName: 'Stacky',
lastName: 'Overflowy',
list: ['zero', 'one', 'two']
},
id: 123
};
console.log(get(myObj, 'user.firstName')); // outputs Stacky
console.log(get(myObj, 'id')); // outputs 123
console.log(get(myObj, 'user.list[1]')); // outputs one
// You can also update values
get(myObj, 'user').firstName = 'John';
A little more involved example with recursion.
function recompose(obj, string) {
var parts = string.split('.');
var newObj = obj[parts[0]];
if (parts[1]) {
parts.splice(0, 1);
var newString = parts.join('.');
return recompose(newObj, newString);
}
return newObj;
}
var obj = { a: { b: '1', c: '2', d:{a:{b:'blah'}}}};
console.log(recompose(obj, 'a.d.a.b')); //blah
2021
You don't need to pull in another dependency every time you wish for new capabilities in your program. Modern JS is very capable and the optional-chaining operator ?. is now widely supported and makes this kind of task easy as heck.
With a single line of code we can write get that takes an input object, t and string path. It works for object and arrays of any nesting level -
const get = (t, path) =>
path.split(".").reduce((r, k) => r?.[k], t)
const mydata =
{ a: { b: [ 0, { c: { d: [ "hello", "world" ] } } ] } }
console.log(get(mydata, "a.b.1.c.d.0"))
console.log(get(mydata, "a.b.1.c.d.1"))
console.log(get(mydata, "a.b.x.y.z"))
"hello"
"world"
undefined
I suggest to split the path and iterate it and reduce the object you have. This proposal works with a default value for missing properties.
const getValue = (object, keys) => keys.split('.').reduce((o, k) => (o || {})[k], object);
console.log(getValue({ a: { b: '1', c: '2' } }, 'a.b'));
console.log(getValue({ a: { b: '1', c: '2' } }, 'foo.bar.baz'));
Many years since the original post.
Now there is a great library called 'object-path'.
https://github.com/mariocasciaro/object-path
Available on NPM and BOWER
https://www.npmjs.com/package/object-path
It's as easy as:
objectPath.get(obj, "a.c.1"); //returns "f"
objectPath.set(obj, "a.j.0.f", "m");
And works for deeply nested properties and arrays.
If you expect to dereference the same path many times, building a function for each dot notation path actually has the best performance by far (expanding on the perf tests James Wilkins linked to in comments above).
var path = 'a.b.x';
var getter = new Function("obj", "return obj." + path + ";");
getter(obj);
Using the Function constructor has some of the same drawbacks as eval() in terms of security and worst-case performance, but IMO it's a badly underused tool for cases where you need a combination of extreme dynamism and high performance. I use this methodology to build array filter functions and call them inside an AngularJS digest loop. My profiles consistently show the array.filter() step taking less than 1ms to dereference and filter about 2000 complex objects, using dynamically-defined paths 3-4 levels deep.
A similar methodology could be used to create setter functions, of course:
var setter = new Function("obj", "newval", "obj." + path + " = newval;");
setter(obj, "some new val");
Other proposals are a little cryptic, so I thought I'd contribute:
Object.prop = function(obj, prop, val){
var props = prop.split('.')
, final = props.pop(), p
while(p = props.shift()){
if (typeof obj[p] === 'undefined')
return undefined;
obj = obj[p]
}
return val ? (obj[final] = val) : obj[final]
}
var obj = { a: { b: '1', c: '2' } }
// get
console.log(Object.prop(obj, 'a.c')) // -> 2
// set
Object.prop(obj, 'a.c', function(){})
console.log(obj) // -> { a: { b: '1', c: [Function] } }
var a = { b: { c: 9 } };
function value(layer, path, value) {
var i = 0,
path = path.split('.');
for (; i < path.length; i++)
if (value != null && i + 1 === path.length)
layer[path[i]] = value;
layer = layer[path[i]];
return layer;
};
value(a, 'b.c'); // 9
value(a, 'b.c', 4);
value(a, 'b.c'); // 4
This is a lot of code when compared to the much simpler eval way of doing it, but like Simon Willison says, you should never use eval.
Also, JSFiddle.
You can use the library available at npm, which simplifies this process. https://www.npmjs.com/package/dot-object
var dot = require('dot-object');
var obj = {
some: {
nested: {
value: 'Hi there!'
}
}
};
var val = dot.pick('some.nested.value', obj);
console.log(val);
// Result: Hi there!
Note if you're already using Lodash you can use the property or get functions:
var obj = { a: { b: '1', c: '2' } };
_.property('a.b')(obj); // => 1
_.get(obj, 'a.b'); // => 1
Underscore.js also has a property function, but it doesn't support dot notation.
I have extended the elegant answer by ninjagecko so that the function handles both dotted and/or array style references, and so that an empty string causes the parent object to be returned.
Here you go:
string_to_ref = function (object, reference) {
function arr_deref(o, ref, i) { return !ref ? o : (o[ref.slice(0, i ? -1 : ref.length)]) }
function dot_deref(o, ref) { return ref.split('[').reduce(arr_deref, o); }
return !reference ? object : reference.split('.').reduce(dot_deref, object);
};
See my working jsFiddle example here: http://jsfiddle.net/sc0ttyd/q7zyd/
You can obtain value of an object member by dot notation with a single line of code:
new Function('_', 'return _.' + path)(obj);
In you case:
var obj = { a: { b: '1', c: '2' } }
var val = new Function('_', 'return _.a.b')(obj);
To make it simple you may write a function like this:
function objGet(obj, path){
return new Function('_', 'return _.' + path)(obj);
}
Explanation:
The Function constructor creates a new Function object. In JavaScript every function is actually a Function object. Syntax to create a function explicitly with Function constructor is:
new Function ([arg1[, arg2[, ...argN]],] functionBody)
where arguments(arg1 to argN) must be a string that corresponds to a valid javaScript identifier and functionBody is a string containing the javaScript statements comprising the function definition.
In our case we take the advantage of string function body to retrieve object member with dot notation.
Hope it helps.
var find = function(root, path) {
var segments = path.split('.'),
cursor = root,
target;
for (var i = 0; i < segments.length; ++i) {
target = cursor[segments[i]];
if (typeof target == "undefined") return void 0;
cursor = target;
}
return cursor;
};
var obj = { a: { b: '1', c: '2' } }
find(obj, "a.b"); // 1
var set = function (root, path, value) {
var segments = path.split('.'),
cursor = root,
target;
for (var i = 0; i < segments.length - 1; ++i) {
cursor = cursor[segments[i]] || { };
}
cursor[segments[segments.length - 1]] = value;
};
set(obj, "a.k", function () { console.log("hello world"); });
find(obj, "a.k")(); // hello world
Use this function:
function dotToObject(data) {
function index(parent, key, value) {
const [mainKey, ...children] = key.split(".");
parent[mainKey] = parent[mainKey] || {};
if (children.length === 1) {
parent[mainKey][children[0]] = value;
} else {
index(parent[mainKey], children.join("."), value);
}
}
const result = Object.entries(data).reduce((acc, [key, value]) => {
if (key.includes(".")) {
index(acc, key, value);
} else {
acc[key] = value;
}
return acc;
}, {});
return result;
}
module.exports = { dotToObject };
Ex:
const user = {
id: 1,
name: 'My name',
'address.zipCode': '123',
'address.name': 'Some name',
'address.something.id': 1,
}
const mappedUser = dotToObject(user)
console.log(JSON.stringify(mappedUser, null, 2))
Output:
{
"id": 1,
"name": "My name",
"address": {
"zipCode": "123",
"name": "Some name",
"something": {
"id": 1
}
}
}
using Array Reduce function will get/set based on path provided.
I tested it with a.b.c and a.b.2.c {a:{b:[0,1,{c:7}]}} and its works for both getting key or mutating object to set value
function setOrGet(obj, path=[], newValue){
const l = typeof path === 'string' ? path.split('.') : path;
return l.reduce((carry,item, idx)=>{
const leaf = carry[item];
// is this last item in path ? cool lets set/get value
if( l.length-idx===1) {
// mutate object if newValue is set;
carry[item] = newValue===undefined ? leaf : newValue;
// return value if its a get/object if it was a set
return newValue===undefined ? leaf : obj ;
}
carry[item] = leaf || {}; // mutate if key not an object;
return carry[item]; // return object ref: to continue reduction;
}, obj)
}
console.log(
setOrGet({a: {b:1}},'a.b') === 1 ||
'Test Case: Direct read failed'
)
console.log(
setOrGet({a: {b:1}},'a.c',22).a.c===22 ||
'Test Case: Direct set failed'
)
console.log(
setOrGet({a: {b:[1,2]}},'a.b.1',22).a.b[1]===22 ||
'Test Case: Direct set on array failed'
)
console.log(
setOrGet({a: {b:{c: {e:1} }}},'a.b.c.e',22).a.b.c. e===22 ||
'Test Case: deep get failed'
)
// failed !. Thats your homework :)
console.log(
setOrGet({a: {b:{c: {e:[1,2,3,4,5]} }}},'a.b.c.e.3 ',22)
)
my personal recommendation.
do not use such a thing unless there is no other way!
i saw many examples people use it for translations for example from json; so you see function like locale('app.homepage.welcome') . this is just bad. if you already have data in an object/json; and you know path.. then just use it directly example locale().app.homepage.welcome by changing you function to return object you get typesafe, with autocomplete, less prone to typo's ..
I copied the following from Ricardo Tomasi's answer and modified to also create sub-objects that don't yet exist as necessary. It's a little less efficient (more ifs and creating of empty objects), but should be pretty good.
Also, it'll allow us to do Object.prop(obj, 'a.b', false) where we couldn't before. Unfortunately, it still won't let us assign undefined...Not sure how to go about that one yet.
/**
* Object.prop()
*
* Allows dot-notation access to object properties for both getting and setting.
*
* #param {Object} obj The object we're getting from or setting
* #param {string} prop The dot-notated string defining the property location
* #param {mixed} val For setting only; the value to set
*/
Object.prop = function(obj, prop, val){
var props = prop.split('.'),
final = props.pop(),
p;
for (var i = 0; i < props.length; i++) {
p = props[i];
if (typeof obj[p] === 'undefined') {
// If we're setting
if (typeof val !== 'undefined') {
// If we're not at the end of the props, keep adding new empty objects
if (i != props.length)
obj[p] = {};
}
else
return undefined;
}
obj = obj[p]
}
return typeof val !== "undefined" ? (obj[final] = val) : obj[final]
}
Few years later, I found this that handles scope and array. e.g. a['b']["c"].d.etc
function getScopedObj(scope, str) {
let obj=scope, arr;
try {
arr = str.split(/[\[\]\.]/) // split by [,],.
.filter(el => el) // filter out empty one
.map(el => el.replace(/^['"]+|['"]+$/g, '')); // remove string quotation
arr.forEach(el => obj = obj[el])
} catch(e) {
obj = undefined;
}
return obj;
}
window.a = {b: {c: {d: {etc: 'success'}}}}
getScopedObj(window, `a.b.c.d.etc`) // success
getScopedObj(window, `a['b']["c"].d.etc`) // success
getScopedObj(window, `a['INVALID']["c"].d.etc`) // undefined
If you wish to convert any object that contains dot notation keys into an arrayed version of those keys you can use this.
This will convert something like
{
name: 'Andy',
brothers.0: 'Bob'
brothers.1: 'Steve'
brothers.2: 'Jack'
sisters.0: 'Sally'
}
to
{
name: 'Andy',
brothers: ['Bob', 'Steve', 'Jack']
sisters: ['Sally']
}
convertDotNotationToArray(objectWithDotNotation) {
Object.entries(objectWithDotNotation).forEach(([key, val]) => {
// Is the key of dot notation
if (key.includes('.')) {
const [name, index] = key.split('.');
// If you have not created an array version, create one
if (!objectWithDotNotation[name]) {
objectWithDotNotation[name] = new Array();
}
// Save the value in the newly created array at the specific index
objectWithDotNotation[name][index] = val;
// Delete the current dot notation key val
delete objectWithDotNotation[key];
}
});
}
If you want to convert a string dot notation into an object, I've made a handy little helper than can turn a string like a.b.c.d with a value of e with dotPathToObject("a.b.c.d", "value") returning this:
{
"a": {
"b": {
"c": {
"d": "value"
}
}
}
}
https://gist.github.com/ahallora/9731d73efb15bd3d3db647efa3389c12
Solution:
function deepFind(key, data){
return key.split('.').reduce((ob,i)=> ob?.[i], data)
}
Usage:
const obj = {
company: "Pet Shop",
person: {
name: "John"
},
animal: {
name: "Lucky"
}
}
const company = deepFind("company", obj)
const personName = deepFind("person.name", obj)
const animalName = deepFind("animal.name", obj)
Here is my implementation
Implementation 1
Object.prototype.access = function() {
var ele = this[arguments[0]];
if(arguments.length === 1) return ele;
return ele.access.apply(ele, [].slice.call(arguments, 1));
}
Implementation 2 (using array reduce instead of slice)
Object.prototype.access = function() {
var self = this;
return [].reduce.call(arguments,function(prev,cur) {
return prev[cur];
}, self);
}
Examples:
var myobj = {'a':{'b':{'c':{'d':'abcd','e':[11,22,33]}}}};
myobj.access('a','b','c'); // returns: {'d':'abcd', e:[0,1,2,3]}
myobj.a.b.access('c','d'); // returns: 'abcd'
myobj.access('a','b','c','e',0); // returns: 11
it can also handle objects inside arrays as for
var myobj2 = {'a': {'b':[{'c':'ab0c'},{'d':'ab1d'}]}}
myobj2.access('a','b','1','d'); // returns: 'ab1d'
I used this code in my project
const getValue = (obj, arrPath) => (
arrPath.reduce((x, y) => {
if (y in x) return x[y]
return {}
}, obj)
)
Usage:
const obj = { id: { user: { local: 104 } } }
const path = [ 'id', 'user', 'local' ]
getValue(obj, path) // return 104
Using object-scan seems a bit overkill, but you can simply do
// const objectScan = require('object-scan');
const get = (obj, p) => objectScan([p], { abort: true, rtn: 'value' })(obj);
const obj = { a: { b: '1', c: '2' } };
console.log(get(obj, 'a.b'));
// => 1
console.log(get(obj, '*.c'));
// => 2
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/object-scan#13.7.1"></script>
Disclaimer: I'm the author of object-scan
There are a lot more advanced examples in the readme.
This is one of those cases, where you ask 10 developers and you get 10 answers.
Below is my [simplified] solution for OP, using dynamic programming.
The idea is that you would pass an existing DTO object that you wish to UPDATE. This makes the method most useful in the case where you have a form with several input elements having name attributes set with dot (fluent) syntax.
Example use:
<input type="text" name="person.contact.firstName" />
Code snippet:
const setFluently = (obj, path, value) => {
if (typeof path === "string") {
return setFluently(obj, path.split("."), value);
}
if (path.length <= 1) {
obj[path[0]] = value;
return obj;
}
const key = path[0];
obj[key] = setFluently(obj[key] ? obj[key] : {}, path.slice(1), value);
return obj;
};
const origObj = {
a: {
b: "1",
c: "2"
}
};
setFluently(origObj, "a.b", "3");
setFluently(origObj, "a.c", "4");
console.log(JSON.stringify(origObj, null, 3));
function at(obj, path, val = undefined) {
// If path is an Array,
if (Array.isArray(path)) {
// it returns the mapped array for each result of the path
return path.map((path) => at(obj, path, val));
}
// Uniting several RegExps into one
const rx = new RegExp(
[
/(?:^(?:\.\s*)?([_a-zA-Z][_a-zA-Z0-9]*))/,
/(?:^\[\s*(\d+)\s*\])/,
/(?:^\[\s*'([^']*(?:\\'[^']*)*)'\s*\])/,
/(?:^\[\s*"([^"]*(?:\\"[^"]*)*)"\s*\])/,
/(?:^\[\s*`([^`]*(?:\\`[^`]*)*)`\s*\])/,
]
.map((r) => r.source)
.join("|")
);
let rm;
while (rm = rx.exec(path.trim())) {
// Matched resource
let [rf, rp] = rm.filter(Boolean);
// If no one matches found,
if (!rm[1] && !rm[2]) {
// it will replace escape-chars
rp = rp.replace(/\\(.)/g, "$1");
}
// If the new value is set,
if ("undefined" != typeof val && path.length == rf.length) {
// assign a value to the object property and return it
return (obj[rp] = val);
}
// Going one step deeper
obj = obj[rp];
// Removing a step from the path
path = path.substr(rf.length).trim();
}
if (path) {
throw new SyntaxError();
}
return obj;
}
// Test object schema
let o = { a: { b: [ [ { c: { d: { '"e"': { f: { g: "xxx" } } } } } ] ] } };
// Print source object
console.log(JSON.stringify(o));
// Set value
console.log(at(o, '.a["b"][0][0].c[`d`]["\\"e\\""][\'f\']["g"]', "zzz"));
// Get value
console.log(at(o, '.a["b"][0][0].c[`d`]["\\"e\\""][\'f\']["g"]'));
// Print result object
console.log(JSON.stringify(o));
Here is my code without using eval. It’s easy to understand too.
function value(obj, props) {
if (!props)
return obj;
var propsArr = props.split('.');
var prop = propsArr.splice(0, 1);
return value(obj[prop], propsArr.join('.'));
}
var obj = { a: { b: '1', c: '2', d:{a:{b:'blah'}}}};
console.log(value(obj, 'a.d.a.b')); // Returns blah
Yes, extending base prototypes is not usually good idea but, if you keep all extensions in one place, they might be useful.
So, here is my way to do this.
Object.defineProperty(Object.prototype, "getNestedProperty", {
value : function (propertyName) {
var result = this;
var arr = propertyName.split(".");
while (arr.length && result) {
result = result[arr.shift()];
}
return result;
},
enumerable: false
});
Now you will be able to get nested property everywhere without importing module with function or copy/pasting function.
Example:
{a:{b:11}}.getNestedProperty('a.b'); // Returns 11
The Next.js extension broke Mongoose in my project. Also I've read that it might break jQuery. So, never do it in the Next.js way:
Object.prototype.getNestedProperty = function (propertyName) {
var result = this;
var arr = propertyName.split(".");
while (arr.length && result) {
result = result[arr.shift()];
}
return result;
};
This is my extended solution proposed by ninjagecko.
For me, simple string notation was not enough, so the below version supports things like:
index(obj, 'data.accounts[0].address[0].postcode');
 
/**
* Get object by index
* #supported
* - arrays supported
* - array indexes supported
* #not-supported
* - multiple arrays
* #issues:
* index(myAccount, 'accounts[0].address[0].id') - works fine
* index(myAccount, 'accounts[].address[0].id') - doesnt work
* #Example:
* index(obj, 'data.accounts[].id') => returns array of id's
* index(obj, 'data.accounts[0].id') => returns id of 0 element from array
* index(obj, 'data.accounts[0].addresses.list[0].id') => error
* #param obj
* #param path
* #returns {any}
*/
var index = function(obj, path, isArray?, arrIndex?){
// is an array
if(typeof isArray === 'undefined') isArray = false;
// array index,
// if null, will take all indexes
if(typeof arrIndex === 'undefined') arrIndex = null;
var _arrIndex = null;
var reduceArrayTag = function(i, subArrIndex){
return i.replace(/(\[)([\d]{0,})(\])/, (i) => {
var tmp = i.match(/(\[)([\d]{0,})(\])/);
isArray = true;
if(subArrIndex){
_arrIndex = (tmp[2] !== '') ? tmp[2] : null;
}else{
arrIndex = (tmp[2] !== '') ? tmp[2] : null;
}
return '';
});
}
function byIndex(obj, i) {
// if is an array
if(isArray){
isArray = false;
i = reduceArrayTag(i, true);
// if array index is null,
// return an array of with values from every index
if(!arrIndex){
var arrValues = [];
_.forEach(obj, (el) => {
arrValues.push(index(el, i, isArray, arrIndex));
})
return arrValues;
}
// if array index is specified
var value = obj[arrIndex][i];
if(isArray){
arrIndex = _arrIndex;
}else{
arrIndex = null;
}
return value;
}else{
// remove [] from notation,
// if [] has been removed, check the index of array
i = reduceArrayTag(i, false);
return obj[i]
}
}
// reduce with the byIndex method
return path.split('.').reduce(byIndex, obj)
}

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
}

Parse JSON-like input containing /regexp/ literals

In my web app, I would like to accept arbitrary JavaScript objects as GET parameters. So I need to parse location.search in a way similar to eval, but I want to create self-contained objects only (object literals, arrays, regexps and possibly restricted-access functions):
var search =
location.search ?
decodeURIComponent(location.search).substring(1).split('&') :
['boo=alert(1)', 'filter={a: /^t/, b: function(i){return i+1;}}']
;
var params = {};
for (var i = 0, temp; i < search.length; i++){
temp = search[i].split('=');
temp = temp[1] ? temp : [temp[0], null];
params[temp[0]] = saferEval(temp[1]);
};
console.log(params);
I came up with a version of saferEval function that blocks access to global variables, but it does not block access to built-in functions like alert():
var saferEval = function(s) {
'use strict';
var deteleGlobals =
'var ' +
Object.getOwnPropertyNames(window)
.join(',')
.replace(/(?:eval|chrome:[^,]*),/g, '') +
';'
;
try {
return eval(deteleGlobals + '(' + s + ');') || s;
} catch(e) {
return s;
};
};
See my jsFiddle - alert(1) code is executed.
Note that top.location is not accessible to jsFiddle scripts, you have to run the code locally if you want to fiddle with actual query parameters like ?filter={a: /%5Cd+/g}.
I would use JSON, but I need to have regular expressions at arbitrary places inside arrays and objects. I do not send any of these object back to the server, so using eval for this shouldn't harm the security so much...
How can I convert a string (that encodes JavaScript object) into object without giving it access to global namespace and built-in functions?
UPDATE - only useful "arbitrary" objects turned out to be regexp literals...
Per your comment that you'd be interested in seeing a solution that just solves the issue of having regex values in your JSON, then you could encode all regex values as strings in normal JSON like this:
"/this is my regex/"
Then, process the JSON normally into a javascript object and then call this function on it which will recursively walk through all objects and arrays, find all items that are strings, check them for the above format and, if found, convert those items to regular expressions. Here's the code:
function isArray(obj) {
return toString.call(obj) === "[object Array]";
}
function isObject(obj) {
return Object.prototype.toString.call(obj) === '[object Object]'
}
var regexTest = /^\/(.*)\/([gimy]*)$/;
function convertRegex(item) {
if (isArray(item)) {
// iterate over array items
for (var i = 0; i < item.length; i++) {
item[i] = convertRegex(item[i]);
}
} else if (isObject(item)) {
for (var prop in item) {
if (item.hasOwnProperty(prop)) {
item[prop] = convertRegex(item[prop]);
}
}
} else if (typeof item === "string") {
var match = item.match(regexTest);
if (match) {
item = new RegExp(match[1], match[2]);
}
}
return item;
}
And a sample usage:
var result = convertRegex(testObj);
Test environment that I stepped through the execution in the debugger: http://jsfiddle.net/jfriend00/bvpAX/
Until there is better solution, I will add alert (and the like) into my list of local variables which would overshadow global/built-in functions within the eval scope:
var deteleGlobals =
'var ' +
Object.getOwnPropertyNames(window)
.join(',')
.replace(/(?:eval|chrome:[^,]*),/g, '') +
',alert,confirm,prompt,setTimeout;'
;
jsFiddle

Converting a string to a javascript associative array

I have a string
string = "masterkey[key1][key2]";
I want to create an associative array out of that, so that it evaluates to:
{
masterkey: {
key1: {
key2: value
}
}
}
I have tried this:
var fullName = string;
fullName = fullName.replace(/\[/g, '["');
fullName = fullName.replace(/\]/g, '"]');
eval("var "+fullName+";");
But I get the error: missing ; before statement with an arrow pointing to the first bracket in ([) "var masterkey["key1"]["key2"];"
I know that eval() is not good to use, so if you have any suggestions, preferably without using it, I'd really appreciate it!
Not the most beautiful, but it worked for me:
var
path = "masterkey[key1][key2]",
scope = {};
function helper(scope, path, value) {
var path = path.split('['), i = 0, lim = path.length;
for (; i < lim; i += 1) {
path[i] = path[i].replace(/\]/g, '');
if (typeof scope[path[i]] === 'undefined') {
scope[path[i]] = {};
}
if (i === lim - 1) {
scope[path[i]] = value;
}
else {
scope = scope[path[i]];
}
}
}
helper(scope, path, 'somevalue');
console.log(scope);
demo: http://jsfiddle.net/hR8yM/
function parse(s, obj) {
s.match(/\w+/g).reduce(function(o, p) { return o[p] = {} }, obj);
return obj;
}
console.dir(parse("masterkey[key1][key2]", {}))
Now try this
string = "masterkey[key1][key2]";
var fullName = string;
fullName = fullName.replace(/\[/g, '[\'');
fullName = fullName.replace(/\]/g, '\']');
document.write("var "+fullName+";");
1) When using eval, the argument you provide must be valid, complete javascript.
The line
var masterkey["key1"]["key2"];
is not a valid javascript statement.
When assigning a value to a variable, you must use =. Simply concatenating some values on to the end of the variable name will not work.
2) var masterkey = ["key1"]["key2"] doesn't make sense.
This looks like an attempt to assign the "key2" property of the "key1" property of nothing to masterkey.
If you want the result to be like the example object you give, then that is what you need to create. That said, parsing the string properly to create an object is better than using regular expressions to translate it into some script to evaluate.

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