Last active
October 13, 2015 15:07
-
-
Save marlun78/4213750 to your computer and use it in GitHub Desktop.
JavaScript URL parser
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* parseUrl | |
* Copyright (c) 2012, marlun78 | |
* MIT License, https://gist.github.com/marlun78/bd0800cf5e8053ba9f83 | |
* | |
* Needs to run in a browser, uses String.prototype.lastIndexOf method. | |
* Regexp stolen from: http://stevenbenner.com/2010/03/javascript-regex-trick-parse-a-query-string-into-an-object/ | |
*/ | |
var parseUrl = (function (element) { | |
var fileName, pathName, pathNames, query, | |
re = /([^?=&]+)(=([^&]*))?/g; | |
function parseQuery (query) { | |
var obj = {}; | |
query.replace(re, function (match, group1, offset, string) { | |
obj[group1] = decodeURIComponent(string); | |
}); | |
return obj; | |
} | |
return function (url) { | |
element.href = url; | |
pathName = element.pathname; | |
if (pathName === '/') { | |
pathNames = []; | |
fileName = ''; | |
} else { | |
pathNames = pathName.substr(1).split('/'); | |
fileName = pathNames[pathNames.length - 1]; | |
} | |
query = element.search; | |
return { | |
fileExtension: fileName.substr(fileName.lastIndexOf('.')), | |
fileName: fileName, | |
hash: element.hash, | |
host: element.host, | |
hostName: element.hostname, | |
pathName: pathName, | |
pathNames: pathNames, | |
port: element.port, | |
protocol: element.protocol, | |
query: query, | |
queryData: query.length > 0 ? parseQuery(query) : null, | |
url: url | |
}; | |
}; | |
}(document.createElement('a'))); | |
//console.clear(); | |
//console.dir(parseUrl('http://sub.example.com:8042/over/there/index.dtb?type=animal&name=narwhal#nose')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment