需求:输入参数名获取url地址中的变量值
window.location 对象所包含的属性
属性 | 描述 |
---|---|
hash | 获取从井号(#)开始的URL(锚) |
host | 主机名和当前URL的端口号 |
hostname | 当前URL的主机名 |
href | 完整的URL |
pathname | 当前URL的路径部分 |
port | 当前URL的端口号 |
protocol | 当前URL的协议 |
search | 从问号(?)开始的URL(查询部分) |
//通过Window.location.search截取参数
function getWindowUrlParams(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
console.log(reg)
//window.location.search可以获取URL地址中从问号 (?) 开始的 URL(查询部分)
var r = window.location.search.substr(1).match(reg);
console.log(r)
/*
注释:ECMAScript v3 已从标准中删除了 unescape() 函数,并反对使用它,
因此应该用 decodeURI() 和 decodeURIComponent() 取而代之。
*/
if (r != null) return decodeURI(r[2]); return null;
}
需求:输入url和参数名获取相应参数的值
//通过传递url和参数名获取参数
function getUrlParams(url, name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)")
const cuturl = url.substr(url.indexOf("?") + 1)
const matchArray = cuturl.match(reg)
if (matchArray) {
return decodeURI(matchArray[2])
}
return null;
}
```