以下是一些在JavaScript中獲取URL參數(shù)的實(shí)現(xiàn)方法:
方法1:使用URLSearchParams對(duì)象/h3>// 假設(shè)當(dāng)前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:使用正則表達(dá)式解析URL
// 假設(shè)當(dāng)前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()方法和數(shù)組操作
// 假設(shè)當(dāng)前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"
聲明:所有內(nèi)容來自互聯(lián)網(wǎng)搜索結(jié)果,不保證100%準(zhǔn)確性,僅供參考。如若本站內(nèi)容侵犯了原著者的合法權(quán)益,可聯(lián)系我們進(jìn)行處理。