頁面 A 跳轉至頁面 B 並攜帶查詢字串(?id=1&name=test),頁面 B 需解析參數。以下提供可直接複製使用的通用函式:
function getUrlParams() {
const params = {};
const search = window.location.search.substring(1); // 去掉 '?'
if (!search) return params;
search.split('&').forEach(pair => {
const [key, value] = pair.split('=');
params[decodeURIComponent(key)] = decodeURIComponent(value || '');
});
return params;
}
// 使用範例
const params = getUrlParams();
console.log(params.id); // "1"
console.log(params.name); // "test"
const params = new URLSearchParams(window.location.search);
const id = params.get('id'); // "1"
const name = params.get('name'); // "test"
// 迭代所有
for (const [k, v] of params) console.log(k, v);
$.urlParam = function(name) {
const results = new RegExp('[?&]' + name + '=([^]*)').exec(window.location.href);
return results ? decodeURIComponent(results[1]) : null;
};
const id = $.urlParam('id');
decodeURIComponent 解碼。?tag=a&tag=b),URLSearchParams.getAll('tag') 可取得陣列。#/page?id=1)需解析 location.hash。掌握這幾種寫法,涵蓋從傳統專案到現代 SPA 的所有參數解析需求。