在頁面開發中,我們常需要從網址中擷取傳入的參數。本文介紹透過 window.location.search 來實現這一功能,經實測可行。
function GetQueryString(name) { var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)","i"); var r = window.location.search.substr(1).match(reg); if (r!=null) return (r[2]); return null; } var sname = GetQueryString("name"); if(sname!=null) { var sname_ = decodeURIComponent(sname); alert(sname_); }
測試方式:存取 abcd.html?name=xyz,程式應該彈出 xyz。
這個方法透過正規表達式比對參數名稱,能準確地從查詢字串中取出對應的值,並透過 decodeURIComponent 進行解碼,避免中文等特殊字元出現亂碼。