萬盛學電腦網

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

JavaScript 獲取 URL 參數的多種高效方法

原生現代方案(推薦)

URLSearchParams API

// 當前頁面 URL
const params = new URLSearchParams(window.location.search);

// 獲取單個參數
const keyword = params.get('keyword');      // "search-term"
const pid = params.get('pid');              // "37"

// 獲取所有同名參數(陣列)
const tags = params.getAll('tag');          // ["js", "css"]

// 判斷是否存在
if (params.has('debug')) { /* ... */ }

// 遍歷所有參數
for (const [key, value] of params) {
  console.log(key, value);
}

優點:原生、無依賴、自動處理編碼/解碼、支援迭代器。

兼容舊環境的工具函數

/**
 * 解析 URL 查詢字符串為物件
 * @param {string} [url=window.location.href] 目標 URL
 * @returns {Object} 參數鍵值對,同名參數取最後一個
 */
function parseQueryString(url = window.location.href) {
  const queryIndex = url.indexOf('?');
  if (queryIndex === -1) return {};
  const queryString = url.slice(queryIndex + 1).split('#')[0]; // 去除 hash
  const params = {};
  queryString.split('&').forEach(pair => {
    const [key, value] = pair.split('=').map(decodeURIComponent);
    if (key) params[key] = value; // 同名覆蓋,若需陣列可改為 params[key] = params[key] ? [].concat(params[key], value) : value
  });
  return params;
}

// 使用
const { keyword, pid } = parseQueryString();
console.log(keyword, pid);

正則表達式快速提取(單參數)

function getParam(name, url = window.location.href) {
  const regex = new RegExp('[?&]' + name + '=([^&#]*)');
  const match = url.match(regex);
  return match ? decodeURIComponent(match[1]) : null;
}

const pid = getParam('pid'); // "37"

注意:正則需轉義特殊字符,且不支援同名多值。

避坑指南

  • 編碼問題:參數值可能包含 %、+、空格等,務必使用 decodeURIComponent 解碼。
  • Hash 干擾:location.search 不包含 # 後內容,但手動傳入完整 URL 時需手動切分。
  • 重複參數:?id=1&id=2,URLSearchParams.get() 取第一個,getAll() 取全部;自定義解析需決定策略。
  • 空值參數:?flag 或 ?flag=,get() 返回空字符串,自定義解析需處理無 = 情況。

總結建議

  • 現代項目:直接用 URLSearchParams。
  • 需兼容 IE:引入 polyfill 或使用工具函數 parseQueryString。
  • 單參數臨時獲取:getParam() 正則法最輕量。
copyright © 萬盛學電腦網 all rights reserved