JS 获取地址栏参数

15 min read
export function getUrlParam(name: string): string | null {
    if (!window.location.search) {
        return null;
    }
    const params = new URLSearchParams(window.location.search);
    return params.get(name);
}
  • 使用 URLSearchParams 会提高代码的可读性和健壮性,但需要注意它在一些旧版浏览器(如 IE11 及以下版本)中不受支持。如果需要支持这些浏览器,可能需要保留原始方法或引入 polyfill。
  • 在实际应用中,确保对输入的参数名称进行适当的检查和编码,以防止潜在的安全问题,特别是在将参数值用于敏感操作时。
export function getUrlParam(name: string): string | null {
    const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)');
    const r = window.location.search.substr(1).match(reg);
    if (r != null) return decodeURIComponent(r[2]);
    return null;
}