把URL变成一个对象返回

效果:

<div id="box"></div>
<script>
var myURL= parseURL("http://www.xiyanghui.com/product/list?id=123456&sort=discount#title");
document.getElementById("box").innerHTML = JSON.stringify(myURL)
function parseURL(url) {  
	var a =  document.createElement('a');  
	a.href = url;  
	return {   
		protocol: a.protocol.replace(':',''),  
		host: a.hostname,  
		port: a.port,   
		query: (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;  
		})(),    
		hash: a.hash.replace('#',''),  
		path: a.pathname.replace(/^([^\/])/,'/$1'),  
	};
} 

var s = {	
	protocol: "http",
    host: "www.xiyanghui.com",
    path: "/product/list",
    query: {
        id: "12345",
        sort: "discount"
    },
    hash: "title"
}

</script>

您可能还喜欢...

发表评论

您的电子邮箱地址不会被公开。