JS快速解析URL

7,962 阅读1分钟
这篇文章会告诉如何用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'));
解析结果:

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