Parsing URLs with the DOM!

Javascript 专栏收录该内容
65 篇文章 1 订阅

它在性能上比parseUri要低一些:

Test code:

var start = +new Date, x = 2000;
while(--x){
  parseURL('http://abc.com:8080/dir/index.html?id=255&m=hello#top');
}
console.log('parseURL: ',+new Date - start);
 
 
var start = +new Date, x = 2000;
while(--x){
  parseUri('http://abc.com:8080/dir/index.html?id=255&m=hello#top');
}
console.log('parseUri: ',+new Date - start);


原文:http://james.padolsey.com/javascript/parsing-urls-with-the-dom/

I hate the DOM! The API sucks! Don’t you agree?

Regardless, we should definitely take advantage of what we’ve been given. So, if something is built into the DOM it would be silly not to use it, right?

Well, that’s what I believe and that’s why I think it’s okay to parse URLs via this API instead of trying to accomplish it in a language-agnostic manner (using a tonne of expensive string operations).

This short function returns an object containing all possible information you would want to retrieve from a URL:

parseURL

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

Usage

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

I’ve tested this solution in all modern browsers (including IE6) and it seems to work perfectly. If you spot any inconsistencies please let me know.

If you don’t feel comfortable using something which relies on the DOM then have a look at thisalthough please note it’s about 12 times slower than the above solution…


  • 0
    点赞
  • 0
    评论
  • 0
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

©️2021 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值