在JavaScript中获取URL参数并进行页面跳转,可以通过以下步骤实现:
URLSearchParams
对象(推荐方式,适用于现代浏览器):URLSearchParams
对象(推荐方式,适用于现代浏览器):获取到参数后,可以使用window.location.href
进行页面跳转:
// 假设我们要跳转到 https://example.com/redirected-page?param1=value1&newParam=newValue
const newUrl = `https://example.com/redirected-page?param1=${encodeURIComponent(param1)}&newParam=newValue`;
window.location.href = newUrl;
假设当前页面URL为 https://example.com/page?param1=value1¶m2=value2
,我们想跳转到 https://example.com/redirected-page
并携带 param1
和一个新的参数 newParam
:
// 获取URL参数
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
const param1 = urlParams.get('param1');
// 构建新的URL并进行跳转
const newUrl = `https://example.com/redirected-page?param1=${encodeURIComponent(param1)}&newParam=newValue`;
window.location.href = newUrl;
null
。null
。encodeURIComponent
对参数值进行编码,确保URL格式正确。encodeURIComponent
对参数值进行编码,确保URL格式正确。URLSearchParams
在现代浏览器中广泛支持,但如果需要兼容旧版浏览器,可以使用正则表达式或字符串操作的方法。通过以上方法,你可以轻松地在JavaScript中获取URL参数并进行页面跳转。
领取专属 10元无门槛券
手把手带您无忧上云