Js控制URL

Js控制URL

浏览器的location对象拥有很多方便的属性用于获取当前URL的组成部分:

  • location.protocol:协议名
  • location.username:用户名
  • location.password:密码
  • location.hostname:主机名
  • location.port:端口号
  • location.host:主机名和端口号
  • location.pathname:路径
  • location.search:查询串
  • location.hash:书签名

在较新(未测试,估计是支持跨域XHR之后的)浏览器中,还有

location.origin:协议名、主机名和端口号
可以使用。

解决方案:

  1. 构造一个HTMLAnchorElement(或者HTMLAreaElement)对象。
  2. 将该对象的href设置为要解析的URL。
  3. 获得对象的相关属性。

HTML


<input type="text" id="url" value="https://github.com:8000/foo?bar#quz" />
<button id="parse">Parse</button>
<pre id="result"></pre>

JS


function parseURL(url) {
    var anchor = document.createElement('a')
    var undefined = void 0
    var parts = {
        protocol: undefined,
        host: undefined,
        port: undefined,
        hostname: undefined,
        pathname: undefined,
        search: undefined,
        hash: undefined
    }
    anchor.href = url
    for (var key in parts) {
        parts[key] = anchor[key]
    }
    return parts
}

document.getElementById('parse').onclick = function () {
    var parts = parseURL(document.getElementById('url').value)
    var text = ''
    for (var key in parts) {
        text += key + ': ' + parts[key] + '\n'
    }
    document.getElementById('result').innerText = text
}

location.origin兼容IE (IE11+才有origin属性)


if (window["context"] == undefined) {  
    if (!window.location.origin) {  
        window.location.origin = window.location.protocol + "//" + window.location.hostname +   
        (window.location.port ? ':' + window.location.port: '');  
    }  
    window["context"] = location.origin+"/V6.0";  
}  
    原文作者:三月四月五月
    原文地址: https://segmentfault.com/a/1190000011698117
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞