方法1:现代浏览器都支持 URL 和 URLSearchParams 对象,可以很方便地从URL中提取参数
// 假设当前URL为 "https://example.com/?name=John&age=30" const url = new URL(window.location.href); // 或者你可以直接传入一个URL字符串 const name = url.searchParams.get('name'); // "John" const age = url.searchParams.get('age'); // "30" 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 } // 假设当前URL为 "https://example.com/?name=John&age=30" const name = getQueryParam('name'); // "John" const age = getQueryParam('age'); // "30" 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; }, {}); } // 假设当前URL为 "https://example.com/?name=John&age=30" const params = getQueryParams(); const name = params['name'];// "John" const age = params['age']; // "30" console.log(name, age);
方法4:使用 location.search 和自定义函数
在 location.search
上构建自己的解析函数,此方法比较简单。
function getQueryParameter(name) { const params = new URLSearchParams(location.search) return params.get(name) } // 假设当前URL为 "https://example.com/?name=John&age=30" const name = getQueryParameter('name'); // "John" const age = getQueryParameter('age'); // "30" console.log(name, age)
总结
到此这篇关于JavaScript获取URL中参数值的四种方法的文章就介绍到这了,更多相关JS获取URL参数值内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
来源链接:https://www.jb51.net/javascript/338795thq.htm
© 版权声明
本站所有资源来自于网络,仅供学习与参考,请勿用于商业用途,否则产生的一切后果将由您(转载者)自己承担!
如有侵犯您的版权,请及时联系3500663466#qq.com(#换@),我们将第一时间删除本站数据。
如有侵犯您的版权,请及时联系3500663466#qq.com(#换@),我们将第一时间删除本站数据。
THE END
暂无评论内容