window.location.href(当前URL)
结果为: http://www.host.com:80/test?keyword=123&username=xxx
window.location.protocol(协议)
结果为: http
window.location.host(域名 + 端口)
结果为: www.host.com:80
window.location.hostname(域名)
结果为: www.host.com
window.location.port(端口)
结果为: 80
window.location.pathname(路径部分)
结果为: test
window.location.search(请求的参数)
结果为: http://www.host.com:80/test?keyword=123&username=xxx
通常由于业务需要,前端页面中的某个数据源来源,需要我们去获取URL的某个参数值。这时封装一个输入参数名获取对应参数值的函数是必不可少的,如下所示:
function getQuery(name) { // 正则:[找寻'&' + 'url参数名字' = '值' + '&']('&'可以不存在) let reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)"); let r = window.location.search.substr(1).match(reg); //substr() 的参数指定的是子串的开始位置和长度,因此它可以替代 substring() 和 slice() 来使用,但是它没有标准化 if(r != null) { // 对参数值进行解码 return decodeURI(r[2]); //decodeURI() 或 decodeURIComponent() } return null; } // 调用方法,注意需要传入String类型的数据,输出结果为String类型 getQuery('keyword'); // '123'
window.location.origin('?'前边的URL)
结果为: http://www.host.com:80/test本文由37°5【https://www.alvinxiao.com 】【https://blog.alvinxiao.com】原创,转载请注明来源。请注意原创和打造和谐的网络环境,谢谢!