方法一:使用URLSearchParams对象
// 假设URL为 http://example.com/?foo=1&bar=2
const searchParams = new URLSearchParams(window.location.search);
const fooParam = searchParams.get('foo'); // 获取参数foo的值,结果为 "1"
const barParam = searchParams.get('bar'); // 获取参数bar的值,结果为 "2"
方法二:使用正则表达式
// 假设URL为http://example.com/?foo=1&bar=2
const urlParams = {};
const regExp = /[?&]+([^=&]+)=([^&]*)/g;
const matches = window.location.href.match(regExp);
matches.forEach(param => {
const [_, key, value] = param.split('=');
urlParams[key] = value;
});
const fooParam = urlParams['foo']; // 获取参数foo的值,结果为 "1"
const barParam = urlParams['bar']; // 获取参数bar的值,结果为 "2"
方法三:使用自定义函数
// 假设URL为 http://example.com/?foo=1&bar=2
function getUrlParam(name) {
const regExp = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
const match = window.location.search.substr(1).match(regExp);
if (match) {
return decodeURI(match[2]);
}
return null;
}
const fooParam = getUrlParam('foo'); // 获取参数foo的值,结果为 "1"
const barParam = getUrlParam('bar'); // 获取参数bar的值,结果为 "2"