• Javascript 利用a标签自动解析URL分析网址实例


    /*
    * @function: 通过a标签解析url标签
    * @param:url  url参数是字符串,解析的目标
      通过IE6-9 chrome  Firefox测试
    *
    */
    function parseURL(url) {
      //创建一个a标签
      var a =  document.createElement('a');
      //将url赋值给标签的href属性。
      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('/') //路径片段
      };
    }
    

      

    测试地址
    console.log(parseURL("http://www.w3school.com.cn/jsref/dom_obj_anchor.asp?type=2#id2"));
    结果如下

    {
    file: "dom_obj_anchor.asp",
    hash: "id2",
    host: "www.w3school.com.cn",
    params: {type: "2"},
    path: "/jsref/dom_obj_anchor.asp",
    port: "80",
    protocol: "http",
    query: "?type=2",
    relative: "/jsref/dom_obj_anchor.asp?type=2#id2",
    segments: [0: "jsref",1: "dom_obj_anchor.asp"],
    source: http://www.w3school.com.cn/jsref/dom_obj_anchor.asp?type=2#id2
    }
    

      

  • 相关阅读:
    【用例篇】Xmind转为csv 导入禅道
    idea替换当前文件内容
    配置IDEA项目JDK环境
    git 只提交部分修改文件
    `总结TESTNG与JUNIT的异同
    POST请求BODY格式区别
    【转】使用AllureReport生成测试报告
    Springboot+Redis 配置和使用
    【转】git branch 命令查看分支、删除远程分支、本地分支
    [转]Json字符串和map和HashMap之间的转换
  • 原文地址:https://www.cnblogs.com/sunshq/p/4386211.html
Copyright © 2020-2023  润新知