将URL解析成像location一样的对象

之前使用Java的API命名做了解析location.search的例子

现在404页面需要分析document.referrer,不能直接拿到search字符串,所以还得想办法把URL解析成像Location一样的对象

可以想象,这种方法浏览器和服务器必须会有,JavaScript实现应该也有了,不过还是写一个玩玩,以显示个人风格:


function parseLocation(url){
	if((typeof url)!="string"||url==""){return null;}
	var urlExp=/^(http:|https:|file:)(?:\/\/)([^\/]*)([^?#]*)([^#]*)(.*)$/ig,
		hostExp=/^([^:]*)((:\d+)?)$/ig;
	var protocol="",
		host="",
		hostname="",
		port="",
		pathname="",
		search="",
		hash="";
	url.replace(urlExp,function(){
		var args=arguments;
		protocol=args[1];
		host=args[2];
		pathname=args[3];
		search=args[4];
		hash=args[5];
	});
	host.replace(hostExp,function(){
		var args=arguments;
		hostname=args[1];
		port=args[2].replace(":","");
	});
	return protocol?{
		protocol:protocol,
		host:host,
		hostname:hostname,
		port:port,
		pathname:pathname,
		search:search,
		hash:hash
	}:null;
}

//have a test
(function(){
	var url="https://www.google.com.hk/search?q=404&rlz=1C1CHRY_enCN481CN481&sugexp=chrome,mod=16&sourceid=chrome&ie=UTF-8#hash";
	var loc=parseLocation(url);
	console.log(loc);
})();


非常简洁,Bug肯定会有,毕竟我没去了解标准URL的规范






[2013-01-27]更新解析方式,使用浏览器的解析方式解析

/**
 * parse a location url to a location like object
 * @param {Object} window
 */
(function(window){
	var a=window.document.createElement("a");
	window.parseLocation=function(url){
		if(!url){return null;}
		a.href=url;
		return {
			href:a.href,
			origin:a.origin||a.protocol+"//"+a.host,
			protocol:a.protocol,
			host:a.host,
			hostname:a.hostname,
			port:a.port,
			pathname:a.pathname,
			search:a.search,
			hash:a.hash
		};
	};
})(window);



你可能感兴趣的:(将URL解析成像location一样的对象)