DEV Community

Discussion on: JavaScript One-Liners That Make Me Excited

Collapse
 
moopet profile image
Ben Sinclair • Edited
// I'd like to see a minifier work that hard.
document.location.search.replace(/(^\?)/,'').split('&').reduce(function(o,n){n=n.split('=');o[n[0]]=n[1];return o},{});

// Challenge accepted.
location.search.substr(1).split('&').reduce((o,n)=>{n=n.split('=');o[n[0]]=n[1];return o},{});
Enter fullscreen mode Exit fullscreen mode

I'm not a big Javascript person so I don't know what the difference is between window.location, document.location and just location (which I assume uses the global window context). I know substr works fine on an empty string, and I'm making the (heroically cavalier) assumption that query strings start with a ? in all browsers' implementations of location.search.

But both of these return something incorrect if there's no query string:

{"": undefined}
Enter fullscreen mode Exit fullscreen mode

Oops. Well, we can do something about that:

(() => {let x=location.search.substr(1).split('&').reduce((o,n)=>{n=n.split('=');o[n[0]]=n[1];return o},{});delete x[""];return x})()
Enter fullscreen mode Exit fullscreen mode

And now it's longer and even less maintainable, but hey :)

Collapse
 
healeycodes profile image
Andrew Healey

This is brilliant, Ben! 😄

Collapse
 
lexlohr profile image
Alex Lohr

I can probably do it in even less characters... let me try:

q={};document.location.search.replace(/([^?&=]+)=([^&]+)/g,(_,k,v)=>q[k]=v);q;
Thread Thread
 
luckybilly profile image
齐翊

Hey, that one could not accept empty value (eg:'?a=&b=1&c=')
try this instead:

//keys should not be empty, but value can
q={};location.search.replace(/([^?&=]+)=([^&]*)/g,(_,k,v)=>q[k]=v);q;