ps: 项目太忙,忘记从哪搬来的了,做个记录收藏一下
- 主要方法代码
// 核心代码
// 获取全部地址栏参数
function getUrlParams() {
var vars = {}
window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,
function(m, key, value) {
vars[key] = value
}
)
return vars
}
// 获取指定地址栏参数
function getUrlKey(name){
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ""])[1].replace(/\+/g, '%20')) || null
}
2.方法应用代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>原生js获取地址栏参数(全部和指定)</title>
<script type="text/javascript">
// 获取全部地址栏参数
function getUrlParams() {
var vars = {}
window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,
function(m, key, value) {
vars[key] = value
}
)
return vars
}
// 获取指定参数
function getUrlKey(name){
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ""])[1].replace(/\+/g, '%20')) || null
}
window.onload = function(){
var urlParams = getUrlParams()
console.log(urlParams, '全部地址栏参数')
var name = getUrlKey('name')
console.log(name, '指定的name')
}
</script>
</head>
<body>
</body>
</html>
3.效果查看

地址栏无参数.png

获取地址栏参数.png