JS获取URL中参数值的4种方法
|
admin
2024年12月28日 20:18
本文热度 1585
|
方法1:现代浏览器都支持 URL 和 URLSearchParams 对象,可以很方便地从URL中提取参数
const url = new URL(window.location.href); const name = url.searchParams.get('name'); const age = url.searchParams.get('age');
console.log(name, age);
方法2:使用正则表达式
可以使用正则表达式匹配URL参数,这种方法相对较低效且较复杂,但也可以做到。
function getQueryParam(name) { const regex = new RegExp('[?&]' + name + '=([^&#]*)', 'i'); const results = regex.exec(window.location.href); return results ? decodeURIComponent(results[1]) : null;}
const name = getQueryParam('name'); const age = getQueryParam('age');
console.log(name, age);
方法3:使用 split 和 reduce
可以通过 split 方法手动拆分查询参数,并用 reduce 将其转化为对象。
function getQueryParams() { return window.location.search .substring(1) .split('&') .reduce((params, param) => { const [key, value] = param.split('='); params[decodeURIComponent(key)] = decodeURIComponent(value || ''); return params; }, {});}
const params = getQueryParams();const name = params['name']; const age = params['age'];
console.log(name, age);
方法4:使用 location.search 和自定义函数
在 location.search 上构建自己的解析函数,此方法比较简单。
function getQueryParameter(name) { const params = new URLSearchParams(location.search); return params.get(name);}
const name = getQueryParameter('name'); const age = getQueryParameter('age');
console.log(name, age);
阅读原文:原文链接
该文章在 2024/12/30 15:54:10 编辑过