• js中url相关


    首先看一个解析url的函数,网址各部分一般格式为http://domain.com/?search=a#hash

    function parseURL(url) {
        var a =  document.createElement('a');   /造一个a元素
        a.href = url;  //a的链接为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('&'),、//把query里面的问号改为空格,并以数组形式返回,按&分隔。在下例中得到id=225 m=hello
                    len = seg.length, i = 0, s;
                for (i;i<len;i++) {
                    if (!seg[i]) { continue; }//没有seach则忽略
                    s = seg[i].split('=');//否则按等号隔开
                    ret[s[0]] = s[1];  id=225   m=hellow
                }
                return ret;返回上面所求
            })(),
            file: (a.pathname.match(//([^/?#]+)$/i) || [,''])[1],  //pathname为路径名,port后面,search前面,z正则表达式有点乱,头大,以后再分析
            hash: a.hash.replace('#',''),//#top变为top
            path: a.pathname.replace(/^([^/])/,'/$1'),//继续乱
            relative: (a.href.match(/tps?://[^/]+(.+)/) || [,''])[1],
            segments: a.pathname.replace(/^//,'').split('/')//无语,看不下去了
        };
    }

    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'
     
  • 相关阅读:
    位集合
    多线程进行http请求
    mysql--测试前缀索引能否用于order by 或者 group by
    用mysql触发器实现log记录
    源码安装mysql
    C语言:void指针
    C语言:枚举类型
    C语言:结构体与数组
    C语言:联合变量
    Linux 基础入门
  • 原文地址:https://www.cnblogs.com/cumting/p/6831532.html
Copyright © 2020-2023  润新知