以下是一些在JavaScript中獲取URL參數的實現方法:
方法1:使用URLSearchParams對象/h3>// 假設當前URL為 http://example.com/?name=john&age=30
const urlParams = new URLSearchParams(window.location.search);
const name = urlParams.get('name'); // "john"
const age = urlParams.get('age'); // "30"
方法2:使用正則表達式解析URL
// 假設當前URL為 http://example.com/?name=john&age=30
function getQueryParam(url, paramName) {
const regex = new RegExp("[?&]" + paramName + "(=([^&#]*)|&|#|$)");
const results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
const name = getQueryParam(window.location.href, 'name'); // "john"
const age = getQueryParam(window.location.href, 'age'); // "30"方法3:使用split()方法和數組操作
// 假設當前URL為 http://example.com/?name=john&age=30
function getQueryParam(paramName) {
const url = window.location.search.substr(1);
const params = url.split('&');
for (let i = 0; i < params.length; i++) {
const param = params[i].split('=');
if (param[0] === paramName) {
return decodeURIComponent(param[1].replace(/\+/g, " "));
}
}
return null;
}
const name = getQueryParam('name'); // "john"
const age = getQueryParam('age'); // "30"聲明:所有內容來自互聯網搜索結果,不保證100%準確性,僅供參考。如若本站內容侵犯了原著者的合法權益,可聯系我們進行處理。