获取URL参数值
- 定义一个函数getUrlParam:利用正则表达式获取url参数的值
javascript
function getUrlParam(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
var r = window.location.search.substr(1).match(reg);
if (r != null) {
return decodeURIComponent(r[2]);
}
return null;
}
示例:假设当前的url为https://www.example.com/index.html?id=123&name=example,则以下代码可以获取到id的值
javascript
var id = getUrlParam('id');
console.log(id); //输出123
- 利用URLSearchParams对象获取URL参数
javascript
var params = new URLSearchParams(window.location.search);
var id = params.get('id');
console.log(id); // 输出123
示例:假设当前的url为https://www.example.com/index.html?id=123&name=example,则以下代码可以获取到id的值
javascript
var params = new URLSearchParams(window.location.search);
var id = params.get('id');
console.log(id); // 输出123
将URL参数转换成json对象
- 定义一个函数parseUrlParam为url参数字符串转换成json对象
javascript
function parseUrlParam(url) {
var params = {};
url.split("?")[1].split("&").forEach(function (param) {
var temp = param.split("=");
params[temp[0]] = temp[1];
});
return params;
}
示例:假设当前的url为https://www.example.com/index.html?id=123&name=example,则以下代码可以获取到包含id和name的json对象
javascript
var params = parseUrlParam(window.location.href);
console.log(params); //{id: "123", name: "example"}
- 利用URLSearchParams对象转换成json对象
javascript
var params = new URLSearchParams(window.location.search);
var obj = {};
for (var key of params.keys()) {
obj[key] = params.get(key);
}
console.log(obj); //{id: "123", name: "example"}
示例:假设当前的url为https://www.example.com/index.html?id=123&name=example,则以下代码可以获取到包含id和name的json对象
javascript
var params = new URLSearchParams(window.location.search);
var obj = {};
for (var key of params.keys()) {
obj[key] = params.get(key);
}
console.log(obj); //{id: "123", name: "example"}
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:JS根据key值获取URL中的参数值及把URL的参数转换成json对象 - Python技术站