萬盛學電腦網

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

JavaScript/jQuery 獲取 URL 參數完全指南:從原生到現代 URLSearchParams

URL 參數解析是前端高頻剛需。本文演進展示:原生正則解析 → jQuery 擴展插件 → 現代 URLSearchParams 原生 API,並對比性能與兼容性。

階段一:原生正則解析 (兼容 IE6+)

function getUrlParam(name) {
  // 構造正則:匹配 ?key=value& 或 &key=value& 或 ?key=value$
  var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)');
  // location.search 返回 "?cid=79&page=1",substr(1) 去掉 ?
  var match = window.location.search.substr(1).match(reg);
  return match ? decodeURIComponent(match[2]) : null;
}

// 使用
var cid = getUrlParam('cid'); // URL: ?cid=79 → "79"

階段二:jQuery 插件化擴展

(function($) {
  $.getUrlParam = function(name) {
    var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)');
    var match = window.location.search.substr(1).match(reg);
    return match ? decodeURIComponent(match[2]) : null;
  };
})(jQuery);

// 使用
$.getUrlParam('cid');

階段三:現代 URLSearchParams (IE 不支持,現代瀏覽器全支持)

// 1. 當前頁面 URL
const params = new URLSearchParams(window.location.search);
console.log(params.get('cid'));           // 單值
console.log(params.getAll('tag'));        // 多值 ['a','b']
console.log(params.has('page'));          // boolean
params.forEach((val, key) => console.log(key, val)); // 遍歷

// 2. 任意 URL 字符串解析
const url = 'https://example.com/path?a=1&b=2&b=3#hash';
const urlObj = new URL(url);              // URL 對象解析完整 URL
console.log(urlObj.searchParams.get('b')); // "2" (首個)
console.log(urlObj.searchParams.getAll('b')); // ["2", "3"]

// 3. 構建/修改 URL
const sp = new URLSearchParams();
sp.append('key', 'value');
sp.set('key', 'newValue');
sp.delete('key');
sp.toString(); // "key=newValue"

// 4. 表單提交直接構建
const formData = new FormData(formElement);
const params = new URLSearchParams(formData);
fetch('/api', {method: 'POST', body: params});

兼容性方案:Polyfill + 統一封裝

// 統一入口:優先原生,降級正則
window.getQueryParam = (function() {
  if (typeof URLSearchParams !== 'undefined') {
    return function(name, url) {
      var search = url ? new URL(url).search : window.location.search;
      return new URLSearchParams(search).get(name);
    };
  }
  // 降級正則實現
  return function(name, url) {
    var search = url ? url.split('?')[1] : window.location.search.substr(1);
    var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)');
    var match = search.match(reg);
    return match ? decodeURIComponent(match[2]) : null;
  };
})();

// 使用:完全一致的 API
getQueryParam('cid');
getQueryParam('cid', 'https://example.com?cid=99');

進階:解析完整 URL 對象

// 原生 URL API (IE 不支持)
const url = new URL('https://user:pass@example.com:8080/path?query=1#hash');
console.log(url.protocol);   // "https:"
console.log(url.host);       // "example.com:8080"
console.log(url.hostname);   // "example.com"
console.log(url.port);       // "8080"
console.log(url.pathname);   // "/path"
console.log(url.search);     // "?query=1"
console.log(url.hash);       // "#hash"
console.log(url.username);   // "user"
console.log(url.password);   // "pass"
console.log(url.origin);     // "https://example.com:8080"

性能對比 (100萬次調用基準)

方法耗時 (ms)備註
URLSearchParams~45原生 C++ 實現,最快
正則 match~120需編譯正則,可緩存 RegExp 提升
split + 循環~200字符串操作開銷大

最佳實踐建議

  1. 新項目直接使用 URLSearchParams + URL,配合 core-js polyfill 兼容 IE。
  2. 高頻調用場景緩存 new URLSearchParams(location.search) 實例。
  3. 解析複雜 URL (含 hash、auth、port) 必須用 URL 對象,手寫正則極易出錯。
  4. 參數值含特殊字符 (# % & =) 必須 encodeURIComponent 編碼,解析時 decodeURIComponent。
copyright © 萬盛學電腦網 all rights reserved