Contents

JavaScript 取得 URL Query String 與 Hash 實用技巧

在前端開發中,經常需要從網址取得 Query String 參數,例如做頁面參數傳遞、SPA 路由、或是根據網址參數顯示不同內容。這篇文章會介紹幾種常見的 JavaScript 取得 Query String 方法,並延伸說明 location.hash、History API 及 URL API 的應用。

常見需求與解決方案

小提示
URL API 只在現代瀏覽器支援,IE 不支援,建議專案要考慮瀏覽器相容性。

取得 Query String 參數

現代瀏覽器已經支援 URL API,讓我們可以很方便地解析網址:

1
2
3
4
const url = new URL(window.location.href);
const params = new URLSearchParams(url.search);
const value = params.get('key'); // 將 "key" 換成你要找的參數名稱
console.log(value);
小提示
URL API 只在現代瀏覽器支援,IE 不支援,建議專案要考慮瀏覽器相容性。

取得所有 Query String 參數

1
2
3
4
const params = new URLSearchParams(window.location.search);
for (const [key, value] of params.entries()) {
  console.log(key, value);
}

動態修改 Query String(不刷新頁面)

1
2
3
4
const params = new URLSearchParams(window.location.search);
params.set('foo', 'bar');
const newUrl = window.location.pathname + '?' + params.toString() + window.location.hash;
window.history.replaceState({}, '', newUrl);

移除/合併/更新參數

1
2
3
4
// 移除參數
params.delete('foo');
// 合併新參數
params.set('newKey', 'newValue');

處理中文或特殊字元(編碼/解碼)

1
2
3
const encoded = encodeURIComponent('中文測試');
const decoded = decodeURIComponent(encoded);
console.log(encoded, decoded);

監聽 location.hash 變化

如果你的頁面有用到 hash 路由(例如 SPA),可以監聽 hash 變化:

1
2
3
window.addEventListener("hashchange", function() {
  console.log("Hash changed:", window.location.hash);
});

取得 hash 內的參數

1
2
3
4
5
6
7
// 假設 hash: #/page?foo=bar
const hash = window.location.hash;
const hashQuery = hash.split('?')[1];
if (hashQuery) {
  const hashParams = new URLSearchParams(hashQuery);
  console.log(hashParams.get('foo'));
}

操作瀏覽器歷史紀錄(History API)

可以用 History API 來控制瀏覽器的前進/後退、pushState 等:

1
2
3
4
5
6
// 新增一筆歷史紀錄
history.pushState({page:1}, "title 1", "?key=value#hash1");
// 監聽 popstate 事件
window.addEventListener('popstate', function(event) {
  console.log('location: ' + document.location + ', state: ' + JSON.stringify(event.state));
});

舊瀏覽器 fallback 寫法

1
2
3
4
function getQueryParam(name) {
  const match = window.location.search.match(new RegExp('([?&]' + name + ')=([^&]*)'));
  return match ? decodeURIComponent(match[2]) : null;
}

常見第三方函式庫

可以用 qsquery-string 處理複雜情境。

1
2
3
4
// 以 query-string 為例
import queryString from 'query-string';
const parsed = queryString.parse(window.location.search);
console.log(parsed);

URL 長度限制與 SEO 注意事項

  • URL 過長(超過 2000 字元)部分瀏覽器或伺服器可能無法處理
  • Query String 參數過多會影響 SEO,建議重要資訊用 path