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

2018-10-20  本文已影响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个或多个

上一篇 下一篇

猜你喜欢

热点阅读