Last active
August 29, 2015 13:55
-
-
Save weirongxu/8781891 to your computer and use it in GitHub Desktop.
js simple url parse.
This file contains hidden or 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
(function() { | |
window.URL = function(href) { | |
this.href = href; | |
this.link = document.createElement('a'); | |
this.link.href = href; | |
this.parse(this); | |
}; | |
window.URL.prototype = { | |
parse: function parse() { | |
var ret = {}, i; | |
var attrs = [ 'href', 'origin', 'hostname', 'host'], | |
reps = [ | |
[ 'search', /^\?/ ], | |
[ 'hash', /^#/ ], | |
[ 'pathname', /^\// ], | |
[ 'protocol', /:$/ ] | |
]; | |
for (i in attrs) | |
this[attrs[i]] = this.link[attrs[i]]; | |
for (i in reps) | |
this[reps[i][0]] = this.link[reps[i][0]].replace(reps[i][1], ''); | |
this.port = this.link.port ? this.link.port : '80'; | |
params = {}; | |
var q_arr = this.search.split("&"); | |
for (i in q_arr) { | |
if (q_arr[i]) { | |
var t = q_arr[i].split("="); | |
params[t[0]] = decodeURI(t[1]); | |
} | |
} | |
this.query = params; | |
}, | |
querySet: function querySet(query) { | |
var q_str = [], i; | |
for (i in query) | |
this.query[i] = query[i]; | |
for (i in this.query) { | |
q_str.push(i + '=' + this.query[i]); | |
} | |
this.link.search = q_str.join('&'); | |
}, | |
queryReSet: function queryReSet(query) { | |
var q_str = []; | |
for (var i in (this.query = query)) { | |
q_str.push(i + '=' + this.query[i]); | |
} | |
this.link.search = q_str.join('&'); | |
}, | |
goto: function goto() { | |
window.location.href = (arguments.length > 0) ? | |
arguments[0] : this.link.href; | |
} | |
}; | |
})(); | |
url = new URL('http://gist.github.com:80/pathname/?search=你好&q=raidou#hash'); | |
console.dir(url); | |
console.log(url.protocol); // http | |
console.log(url.hostname); // gist.github.com | |
console.log(url.port); // 80 | |
console.log(url.pathname); // pathname/ | |
console.log(url.search); // search=%E4%BD%A0%E5%A5%BD&q=raidou | |
console.log(url.hash); // hash | |
console.log(url.host); // gist.github.com | |
console.log(url.query); // {search: "你好", q: "raidou"} | |
url.querySet({test:'你好'}); // {search: "你好", q: "raidou", test: "你好"} | |
console.log(url.query); | |
url.queryReSet({test:'你好'}); // {test: "你好"} | |
console.log(url.query); | |
url.link.href = 'https://gist.github.com/weirongxu/8781891'; | |
console.log(url); | |
url.parse(); | |
console.log(url); | |
// url.goto(); | |
// url.goto('https://github.com'); | |
var this_url = new URL(window.location.href); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment