首页 专题 H5案例 前端导航 UI框架

JS快速解析URL

作者:TG 日期: 2018-08-09 字数: 1893 阅读: 5922
这篇文章会告诉如何用JS快速的解析一个URL,得到协议(protocol)域名(host)端口(port)查询字符串(query)等信息。

使用<a>元素或URL对象快速解析:

function parseURL(url) {

  var a = document.createElement('a');

  a.href = url;

  // var a = new URL(url);

  return {

    source: url,

    protocol: a.protocol.replace(':', ''), 

    host: a.hostname,

    port: a.port,

    query: a.search,

    params: (function() {

      var params = {},

          seg = a.search.replace(/^\?/, '').split('&'),

          len = seg.length,

          p;

      for (var i = 0; i < len; i++) {

        if (seg[i]) {

           p = seg[i].split('=');

           params[p[0]] = p[1];

        }

      }

      return params;

   })(),

   hash: a.hash.replace('#', ''),

   path: a.pathname.replace(/^([^\/])/, '/$1')

  };

}


console.log(parseURL('https://test.com:8080/path/index.html?name=angle&age=18#top'));

解析结果:


如有疑问,欢迎在下方评论区留言!


目录