Instantly share code, notes, and snippets.

Embed
What would you like to do?
Parse hash bang HTTP GET query style arguments from an URL using Javascript
/**
* Parse hash bang parameters from a URL as key value object.
*
* For repeated parameters the last parameter is effective.
*
* If = syntax is not used the value is set to null.
*
* #x&y=3 -> { x:null, y:3 }
*
* @param aURL URL to parse or null if window.location is used
*
* @return Object of key -> value mappings.
*/
function parseHashBangArgs(aURL) {
aURL = aURL || window.location.href;
var vars = {};
var hashes = aURL.slice(aURL.indexOf('#') + 1).split('&');
for(var i = 0; i < hashes.length; i++) {
var hash = hashes[i].split('=');
if(hash.length > 1) {
vars[hash[0]] = hash[1];
} else {
vars[hash[0]] = null;
}
}
return vars;
}
@zaus

This comment has been minimized.

Show comment
Hide comment
@zaus

zaus Mar 20, 2013

line 19: missing the "bang" in the "hashbang" -- should be aUrl.indexOf('#!')+2

zaus commented Mar 20, 2013

line 19: missing the "bang" in the "hashbang" -- should be aUrl.indexOf('#!')+2

@jwilsjustin

This comment has been minimized.

Show comment
Hide comment
@jwilsjustin

jwilsjustin Mar 21, 2013

This is great!

jwilsjustin commented Mar 21, 2013

This is great!

@tonytopper

This comment has been minimized.

Show comment
Hide comment
@tonytopper

tonytopper Jun 12, 2013

Thanks for this.

tonytopper commented Jun 12, 2013

Thanks for this.

@hercegyu

This comment has been minimized.

Show comment
Hide comment
@hercegyu

hercegyu Jan 10, 2014

You can add support for full urls in # part, example '...#somepage.php?x=11&y=yes'

function parseHashBangArgs(aURL) {

aURL = aURL || window.location.href;
var vars = {};
var hashes = aURL.slice(aURL.indexOf('#') + 1).split('?');
if(hashes.length > 1) {
    vars['page'] = hashes[0];
    hashes = hashes[1].split('&');
} else {
    hashes = hashes[0].split('&');
}

for(var i = 0; i < hashes.length; i++) {
    var hash = hashes[i].split('=');
    if(hash.length > 1) {
        vars[hash[0]] = hash[1];
    } else {
        vars[hash[0]] = null;
    }
}

return vars;

}

hercegyu commented Jan 10, 2014

You can add support for full urls in # part, example '...#somepage.php?x=11&y=yes'

function parseHashBangArgs(aURL) {

aURL = aURL || window.location.href;
var vars = {};
var hashes = aURL.slice(aURL.indexOf('#') + 1).split('?');
if(hashes.length > 1) {
    vars['page'] = hashes[0];
    hashes = hashes[1].split('&');
} else {
    hashes = hashes[0].split('&');
}

for(var i = 0; i < hashes.length; i++) {
    var hash = hashes[i].split('=');
    if(hash.length > 1) {
        vars[hash[0]] = hash[1];
    } else {
        vars[hash[0]] = null;
    }
}

return vars;

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment