解析url中的信息

用‘http://example.com:8000/pathname?search=test#hash’为例:

let queryUrl = function (url = window.location.href) {
  let _url = document.createElement('a');
  _url.href = url;
  return {
    protocol :_url.protocol,//'http'
    host :_url.host,//'example.com:8000'
    hostname :_url.hostname,//'example.com'
    port :_url.port ? _url.port :'80',//'8000',
    pathname : _url.pathname,//'/pathname/'
    search :_url.search,//'?search=test'
    hash :_url.hash,//‘#hash’
  }        
}

调用方法queryUrl,可以获取url中的信息。

若参数url为空,则默认去当前浏览器的url作为参数。

posted @ 2018-05-22 14:56  逐路  阅读(140)  评论(0)    收藏  举报