<?php

Currently browsing parse_url

javascript版本的parse_url函数

在很多时候我们需要通过javascript在页面中获取GET方式传递的各个参数,很可惜javascript没有源生的支持。在PHP中可以通过parse_url函数来获取一个URL中所包含的各个参数及其他信息。以前我写过一个类似parse_url的js函数,不过只是提取参数,其他信息就直接抛弃了。今天看到另外一个比较完全的版本,一起放出来跟大家分享一下吧:)

首先是以前我的版本:

/*
 * @author zhys9
 * @date 20071010
 * @param String string URL
 * @return Object oRs
 * e.g. input: 'http://so.56.com/index?type=video&key=aaa'
 * 		ouput: {'type':video, 'key':'aaa'}
 */
function parse_str(string){
	var a = [];
	var oRs = {};
	var query = string.substr(string.indexOf('?')+1);
	var tmp = query.split('&');
	var k;
	for(var i=0;i<tmp.length;i++){
		a = tmp[i].split('=');
		oRs[a[0]] = a[1];
	}
	return oRs;
}

欠缺的地方就是单纯的字符串解析,没有获取协议、端口、域名、锚点等信息
下面再看一下比较完整的版本:

// This function creates a new anchor element and uses location
// properties (inherent) to get the desired URL data. Some String
// operations are used (to normalize results across browsers).

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(/tp:\/\/[^\/]+(.+)/) || [,''])[1],
        segments: a.pathname.replace(/^\//,'').split('/')
    };
}

比较巧妙的是利用了A标签的DOM属性来获取更多的信息。不过,在document.location对象中包含了所有的信息,只是用这种方法只能获取document.location的信息,不具有更好的通用性。
用法:

var myURL = parseURL('http://zhys9.com:8080/blog/index.php?id=255&m=hello#top');

myURL.file;     // = 'index.php'
myURL.hash;     // = 'top'
myURL.host;     // = 'zhys9.com'
myURL.query;    // = '?id=255&m=hello'
myURL.params;   // = Object = { id: 255, m: hello }
myURL.path;     // = '/blog/index.php'
myURL.segments; // = Array = ['dir', 'index.php']
myURL.port;     // = '8080'
myURL.protocol; // = 'http'
myURL.source;   // = 'http://zhys9.com:8080/blog/index.php?id=255&m=hello#top'

比较完整的这个版本的代码取自:http://james.padolsey.com/javascript/parsing-urls-with-the-dom/