萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 獲取 URL 參數完整指南:從傳統正則到現代 URLSearchParams

獲取 URL 查詢參數是前端路由、數據傳遞、埋點分析的基礎技能。從早期的正則匹配到現代 URLSearchParams API,本文系統梳理各種方案的優缺點、兼容性、性能與最佳實踐,助你選對工具、寫對代碼。

URL 結構基礎

https://example.com/path/page?name=value&id=123#hash
│           │           │              │
│           │           │              └─ hash (錨點,不發送給服務器)
│           │           └─ search (查詢字符串,含 ?)
│           └─ pathname
└─ origin (protocol + host)

方案對比總覽

方案API/方法瀏覽器支持優點缺點推薦指數
正則匹配手寫 RegExp全支持 (IE6+)無依賴、可控性強易出錯、需手動 decode、不支持多值同名⭐⭐ (舊項目維護)
split/循環解析字符串分割全支持邏輯直觀性能差、繁瑣、同樣需手動 decode⭐ (教學用)
URLSearchParamsnew URLSearchParams(search)IE 無支持,現代全支持標準 API、自動編解碼、支持多值、鏈式操作IE 需 polyfill⭐⭐⭐⭐⭐ (現代首選)
URL 對象new URL(href)IE 無支持,現代全支持解析完整 URL、屬性訪問便捷IE 需 polyfill、較重⭐⭐⭐⭐ (需解析完整 URL 時)
第三方庫query-string, qs全支持功能豐富(嵌套對象、數組)、Node 同構增加體積⭐⭐⭐ (複雜場景)

方案一:現代標準 — URLSearchParams (推薦)

// 1. 從當前頁面獲取
const params = new URLSearchParams(window.location.search);

// 2. 從任意 URL 字符串獲取
const url = 'https://example.com?name=张三&id=123&tag=js&tag=ts';
const params2 = new URLSearchParams(new URL(url).search);

// 核心操作
params.get('name');        // '张三' (首個值,自動 decode)
params.getAll('tag');      // ['js', 'ts'] (所有值)
params.has('id');          // true
params.keys();             // 迭代器: 'name', 'id', 'tag'
params.values();           // 迭代器: '张三', '123', 'js', 'ts'
params.entries();          // 迭代器: ['name','张三'], ['id','123']...
params.toString();         // 'name=张三&id=123&tag=js&tag=ts' (自動 encode)
[...params];               // [['name','张三'], ['id','123'], ['tag','js'], ['tag','ts']]

// 修改操作 (會改變實例)
params.set('id', '456');      // 設置/替換
params.append('tag', 'vue');  // 追加同名值
params.delete('name');        // 刪除
params.sort();                // 按鍵名排序

轉為普通對象 (單值模式,同名取最後)

const obj = Object.fromEntries(params); 
// { name: '张三', id: '456', tag: 'vue' }

轉為對象 (同名合併為數組)

const obj = {};
for (const [k, v] of params) {
  if (obj[k] === undefined) obj[k] = v;
  else obj[k] = Array.isArray(obj[k]) ? [...obj[k], v] : [obj[k], v];
}
// { name: '张三', id: '456', tag: ['js', 'ts', 'vue'] }

方案二:URL 對象 (需解析完整 URL 時)


const url = new URL('https://example.com/path?name=value#hash');
url.searchParams.get('name'); // 'value'
url.origin;     // 'https://example.com'
url.hostname;   // 'example.com'
url.pathname;   // '/path'
url.hash;       // '#hash'
url.href;       // 完整 URL

// 修改參數並獲取新 URL
url.searchParams.set('page', '2');
url.toString(); // 'https://example.com/path?name=value&page=2#hash'

方案三:傳統正則方案 (兼容 IE / 無構建環境)


function getQueryParam(name, url = window.location.href) {
  // 1. 提取 search 部分 (去掉 #hash)
  const search = url.split('#')[0].split('?')[1] || '';
  // 2. 正則匹配: 參數名=值(&或結尾)
  // 注意:參數名需轉義特殊字符
  const regex = new RegExp('[?&]' + name.replace(/[\[\]]/g, '\\$&') + '=([^&]*)');
  const match = search.match(regex);
  return match ? decodeURIComponent(match[1].replace(/\+/g, ' ')) : null;
}

// 獲取所有參數對象
function getAllParams(url = window.location.href) {
  const search = url.split('#')[0].split('?')[1] || '';
  const params = {};
  search.split('&').forEach(pair => {
    const [key, val = ''] = pair.split('=');
    const decodedKey = decodeURIComponent(key.replace(/\+/g, ' '));
    const decodedVal = decodeURIComponent(val.replace(/\+/g, ' '));
    if (params[decodedKey] === undefined) params[decodedKey] = decodedVal;
    else params[decodedKey] = Array.isArray(params[decodedKey]) ? [...params[decodedKey], decodedVal] : [params[decodedKey], decodedVal];
  });
  return params;
}

方案四:Node.js / 同構環境


// Node.js 18+ 原生支持 URL, URLSearchParams
const { URL, URLSearchParams } = require('url'); // 或全局可用

// 處理複雜嵌套對象/數組 (如 a[b]=1&a[c]=2 → {a:{b:1,c:2}})
// 推薦使用成熟庫: qs (Express 默認), query-string
const qs = require('qs');
qs.parse('a[b]=1&a[c]=2'); // { a: { b: '1', c: '2' } }
qs.stringify({ a: { b: 1, c: 2 } }); // 'a[b]=1&a[c]=2'

IE 兼容性處理 (Polyfill)


// 1. 官方 polyfill (推薦)
<script src="https://cdn.jsdelivr.net/npm/url-search-params-polyfill@latest/url-search-params.js"></script>

// 2. 或 core-js
import 'core-js/stable/url-search-params';
import 'core-js/stable/url';

// 3. 簡易 polyfill (僅基礎 get/getAll/set/append/delete/toString)
if (typeof URLSearchParams === 'undefined') {
  window.URLSearchParams = function(search) { /* 簡易實現 */ };
}

實戰最佳實踐模式

1. 封裝通用 Hook/工具函數


// useQueryParams.js (Vue 3 Composition API / React Hook)
export function useQueryParams() {
  const params = new URLSearchParams(window.location.search);
  
  const get = (key) => params.get(key);
  const getAll = (key) => params.getAll(key);
  const getNumber = (key, defaultVal = 0) => Number(params.get(key)) || defaultVal;
  const getBoolean = (key) => params.get(key) === 'true';
  
  const set = (key, val) => {
    params.set(key, val);
    updateUrl();
  };
  
  const remove = (key) => {
    params.delete(key);
    updateUrl();
  };
  
  function updateUrl() {
    const newUrl = `${location.origin}${location.pathname}?${params.toString()}${location.hash}`;
    history.replaceState(null, '', newUrl); // 不添加歷史記錄
    // 或 history.pushState(null, '', newUrl); // 添加歷史記錄
  }
  
  return { params, get, getAll, getNumber, getBoolean, set, remove };
}

2. 類型安全獲取 (TypeScript)


interface QueryParams {
  page: number;
  size: number;
  keyword?: string;
  tags?: string[];
}

function getTypedParams>(): Partial {
  const params = new URLSearchParams(window.location.search);
  const result = {} as Partial;
  
  for (const key of params.keys()) {
    const vals = params.getAll(key);
    // 簡單類型推斷:數字、布爾、數組
    if (vals.length === 1) {
      const v = vals[0];
      if (/^\d+$/.test(v)) result[key] = Number(v);
      else if (v === 'true' || v === 'false') result[key] = v === 'true';
      else result[key] = v;
    } else {
      result[key] = vals;
    }
  }
  return result;
}

常見坑點避雷

  • 編碼問題:`+` 在 application/x-www-form-urlencoded 中代表空格,`decodeURIComponent` 不處理 `+`,**需先 `.replace(/\+/g, ' ')` 再 `decodeURIComponent`**。URLSearchParams 內部已正確處理。
  • 重複參數名:`params.get('tag')` 只返回第一個,必須用 `getAll()` 獲取所有。
  • Hash 干擾:`window.location.search` 不包含 hash,但手動解析完整 URL 時需先 `.split('#')[0]` 去除 hash。
  • 空值參數:`?flag` 或 `?key=` → `params.get('key')` 返回 `''` (空字符串),`params.has('key')` 返回 `true`。
  • 大小寫敏感:參數名區分大小寫 (`id` ≠ `ID`),但某些後端框架不區分,需約定統一規範。

總結

現代項目首選 URLSearchParams:標準化、自動編解碼、支持多值、鏈式 API、輕量。配合 core-js polyfill 完美兼容 IE。
需解析完整 URL 時用 new URL()。
複雜嵌套對象序列化用 qs/query-string。
避免手寫正則/分割解析,極易踩編碼、多值、邊界坑。
封裝通用工具函數/Hook,統一項目參數獲取規範,提升開發效率與代碼質量。

copyright © 萬盛學電腦網 all rights reserved