<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>获取网页url中的参数</title>
</head>
<body>
<script>
//方法1
var parseQueryString = function (url, key) {
var num = url.indexOf('?'); // 获取 ?的下标
if (num > 0) {
url = url.slice(num + 1); // 截取 url ?后面的所有参数
var arr = url.split('&'); // 将各个参数放到数组里
var result = {}; // 存放结果
for (var i = 0; i < arr.length; i++) {
num = arr[i].indexOf('='); // 使用 = 对 name 和 value 进行划分
if (num > 0) {
var name = arr[i].slice(0, num); // 获取 name 值
var value = arr[i].slice(num + 1); // 获取 value 值
result[name] = value;
}
}
if (!result[key] || key == "" || key == null) {
return "";
} else {
return result[key];
}
}
}
var result1 = parseQueryString('https://www.didichuxing.com/path?key1=a&key2=123&key3=中国', 'key1'); // a
var result2 = parseQueryString('https://www.didichuxing.com/path?key1=a&key2=123&key3=中国', 'key2'); // 123
var result3 = parseQueryString('https://www.didichuxing.com/path?key1=a&key2=123&key3=中国', 'key3'); // 中国
console.log(result1,result2,result3);
//方法2 获取当前页面的url中的参数值
function getUrlParam(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
var r = window.location.search.substr(1).match(reg);
if (r != null) return decodeURI(r[2]);
return null;
}
</script>
</body>
</html>