Skip to content

Instantly share code, notes, and snippets.

@mindfullsilence
Created September 5, 2015 22:11
Show Gist options
  • Save mindfullsilence/d6787d35e969690a9efc to your computer and use it in GitHub Desktop.
Save mindfullsilence/d6787d35e969690a9efc to your computer and use it in GitHub Desktop.
Get url parameters as as a JS Location object complete with query params
/**
* Created by Tim on 9/5/15.
* Special thanks to James Padolsey:
* http://james.padolsey.com/javascript/parsing-urls-with-the-dom/
*
* Seriously, why didn't I think of that???
*
* Pretty much the same code as link above. Cleaned up the regex a bit to avoid
* false errors in IDEs. Added some checks so we default to the document
* location if nothing is passed. I also check to see if the string passed is a
* valid URL. If not, we return an empty object.
*/
var getLinkParams = function getLinkParams(url) {
var a;
// if parameter was passed rather than binding
if(typeof url !== 'undefined') {
return getLinkParams.call(url);
}
// if no parameter and not instantiated
if(typeof url === 'undefined' && this instanceof Window) {
return getLinkParams.call(document.location.href);
}
// if not an actual url
if(!/^(https?|ftp|file):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(this.toString())) {
console.warn('The variable passed to getLinkParams was not a valid url, and so could not be parsed. You entered: \n\''+this.toString()+'\' \n\nReturning an empty object');
return {};
}
a = document.createElement('a');
a.href = this.toString();
return {
source: this.toString(),
protocol: a.protocol.replace(':',''),
host: a.hostname,
port: a.port,
query: a.search,
params: (function(){
var ret = {},
seg = a.search.replace(/^\?/,'').split('&'),
len = seg.length, i = 0, s;
for (;i<len;i++) {
if (!seg[i]) { continue; }
s = seg[i].split('=');
ret[s[0]] = s[1];
}
return ret;
})(),
file: (a.pathname.match(/\/\/([^\/?#]+)$/i) || [,''])[1],
hash: a.hash.replace('#',''),
path: a.pathname.replace(/^([^\/])/,'/$1'),
relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [,''])[1],
segments: a.pathname.replace(/^\/\//,'').split('/')
}
};
@mindfullsilence
Copy link
Author

var docLink = getLinkParams();
var link = 'http://example.com/sub?key=value#elementId'

// The following are equivalent:
var linkParams = getLinkParams(link);
var linkParams = getLinkParams.call(link);

var notALink = getLinkParams(42);

Will log the following:

console.dir(docLink)
{
    "source": "https://gist.github.com/mindfullsilence/d6787d35e969690a9efc",
    "protocol": "https",
    "host": "gist.github.com",
    "port": "",
    "query": "",
    "params": {},
    "file": "",
    "hash": "",
    "path": "/mindfullsilence/d6787d35e969690a9efc",
    "relative": "/mindfullsilence/d6787d35e969690a9efc",
    "segments": [
        "",
        "mindfullsilence",
        "d6787d35e969690a9efc"
    ]
}


console.dir(linkParams);
{
    "source": "http://example.com/sub?key=value#elementId",
    "protocol": "http",
    "host": "example.com",
    "port": "",
    "query": "?key=value",
    "params": {
        "key": "value"
    },
    "file": "",
    "hash": "elementId",
    "path": "/sub",
    "relative": "/sub?key=value#elementId",
    "segments": [
        "",
        "sub"
    ]
}

console.dir(notALink);
{}

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