-
-
Save zenwalk/eeac1f4df48a09038389 to your computer and use it in GitHub Desktop.
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
var parser = function(url) { | |
var a = document.createElement('a'); | |
a.href = url; | |
var search = function(search) { | |
if(!search) return {}; | |
var ret = {}; | |
search = search.slice(1).split('&'); | |
for(var i = 0, arr; i < search.length; i++) { | |
arr = search[i].split('='); | |
ret[arr[0]] = arr[1]; | |
} | |
return ret; | |
}; | |
return { | |
protocol: a.protocol, | |
host: a.host, | |
hostname: a.hostname, | |
pathname: a.pathname, | |
search: search(a.search), | |
hash: a.hash | |
} | |
}; | |
var url = 'http://sub.example.com:8023/home/?foo=bar&ciao=cc#hash'; | |
parser(url); | |
// 结果是? | |
// ==================================================== | |
(function(exportName) { | |
// var url = 'http://sub.example.com:8023/home/?foo=bar&ciao=cc#hash'; | |
// console.log(JSON.stringify(jurls.parser(url), null, 2)); | |
var exports = exports || {}; | |
var urlCaches = {}; | |
var urlElement; | |
var urlAttrs = ['protocol', 'host', 'hostname', 'pathname', 'search', 'hash', 'port']; | |
var parser = function(url) { | |
if (urlCaches[url]) { | |
return urlCaches[url]; | |
} | |
if (!urlElement) { | |
urlElement = document.createElement('a'); | |
} | |
urlElement.href = url; | |
var result = {}; | |
for (var i = 0; i < urlAttrs.length; i++) { | |
result[urlAttrs[i]] = urlElement[urlAttrs[i]]; | |
} | |
urlCaches[url] = result; | |
return result; | |
}; | |
exports.parser = parser; | |
if (typeof define === 'function') { | |
if (define.amd || define.cmd) { | |
define(function() { | |
return exports; | |
}); | |
} | |
} else if (typeof module !== 'undefined' && module.exports) { | |
module.exports = exports; | |
} else { | |
window[exportName] = exports; | |
} | |
})('jurls'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment