美文网首页
获取url协议,域名,端口号

获取url协议,域名,端口号

作者: 安逸的蓝鲸 | 来源:发表于2018-10-20 16:15 被阅读0次

    方法1: 简便方式,利用window.location的属性

    属性
    href 完整的url
    protocol 协议
    hostname 主机名
    hostname 主机名+端口
    host 端口
    pathname 路径部分
    search 查询部分
    hash #开始的锚
    若url= 'http://www.baidu.com:8080/cd/a?a=1&b=2#active'
    则:
    window.location.href => 'http://www.baidu.com:8080?a=1&b=2#active'
    window.location.protocol=>'http'
    window.location.port=>8080
    window.location.search=>'?a=1&b=2'
    window.location.pathname=>'/cd/a'
    window.location.hash=>'#active'
    

    方法2:用正则匹配

    var str = 'http://www.baidu.com:8080?a=1&b=2#active'
    var arr = str.match(/(\w+):\/\/([^/:]+):(\d*)?/)
    console.log(arr)  //["http://www.baidu.com:8080", "http", "www.baidu.com", "8080"]
    

    正则解析:
    1 (\w+) 表示字母数字下划线的一个或多个字符
    2 ([^/:]+) 表示非/或非:的任意字符的一个或多个
    3 (\d*) 表示数字的0个或多个

    相关文章

      网友评论

          本文标题:获取url协议,域名,端口号

          本文链接:https://www.haomeiwen.com/subject/ftdmzftx.html