Js解析URL

/**
 *@param {string} url 完整的URL地址 
 *@returns {object} 自定義的對象 
 **/
function parseURL(url) {
	var a = document.createElement('a');
	a.href = url;
	return {
		source: url,
		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('/')
	};
}

1, window.location.href
整個URl字符串(在瀏覽器中就是完整的地址欄)javascript

2,window.location.protocol
URL 的協議部分
本例返回值:http:java

3,window.location.host
URL 的主機部分
本例返回值:www.jb51.net瀏覽器

4,window.location.port
URL 的端口部分
若是採用默認的80端口(update:即便添加了:80),那麼返回值並非默認的80而是空字符
本例返回值:」"url

5,window.location.pathname
URL 的路徑部分(就是文件地址)
本例返回值:/seo/.net

6,window.location.search
查詢(參數)部分
除了給動態語言賦值之外,咱們一樣能夠給靜態頁面,並使用javascript來得到相信應的參數值
本例返回值:?ver=1.0&id=6code

7,window.location.hash
錨點對象

相關文章
相關標籤/搜索