最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

JavaScript獲取URL中參數(shù)值的四種方法

 更新時(shí)間:2025年04月01日 10:35:43   作者:夕陽_醉了  
在前端開發(fā)中,處理URL參數(shù)是一個(gè)常見的任務(wù),尤其是在沒有框架支持的情況下,這篇文章主要介紹了JavaScript獲取URL中參數(shù)值的四種方法,需要的朋友可以參考下

方法1:現(xiàn)代瀏覽器都支持 URL 和 URLSearchParams 對(duì)象,可以很方便地從URL中提取參數(shù)

// 假設(shè)當(dāng)前URL為 "https://example.com/?name=John&age=30"
const url = new URL(window.location.href); 
// 或者你可以直接傳入一個(gè)URL字符串
const name = url.searchParams.get('name'); // "John"
const age = url.searchParams.get('age'); // "30"
console.log(name, age);

方法2:使用正則表達(dá)式

可以使用正則表達(dá)式匹配URL參數(shù),這種方法相對(duì)較低效且較復(fù)雜,但也可以做到。

function getQueryParam(name) {
  const regex = new RegExp('[?&]' + name + '=([^&#]*)', 'i')
  const results = regex.exec(window.location.href)
  return results ? decodeURIComponent(results[1]) : null
}
// 假設(shè)當(dāng)前URL為 "https://example.com/?name=John&age=30"
const name = getQueryParam('name'); // "John"
const age = getQueryParam('age'); // "30"
console.log(name, age)

方法3:使用 split 和 reduce

可以通過 split 方法手動(dòng)拆分查詢參數(shù),并用 reduce 將其轉(zhuǎn)化為對(duì)象。

function getQueryParams() {    
    return window.location.search
    .substring(1) // 去掉 ?        
    .split('&') // 按 & 拆分       
    .reduce((params, param) => {            
        const [key, value] = param.split('=');            
        params[decodeURIComponent(key)] = decodeURIComponent(value || '');            
        return params;        
    }, {});
}
// 假設(shè)當(dāng)前URL為 "https://example.com/?name=John&age=30"
const params = getQueryParams();
const name = params['name'];// "John"
const age = params['age']; // "30"
console.log(name, age);

方法4:使用 location.search 和自定義函數(shù)

在 location.search 上構(gòu)建自己的解析函數(shù),此方法比較簡單。

function getQueryParameter(name) {
  const params = new URLSearchParams(location.search)
  return params.get(name)
}
// 假設(shè)當(dāng)前URL為 "https://example.com/?name=John&age=30"
const name = getQueryParameter('name'); // "John"
const age = getQueryParameter('age'); // "30"
console.log(name, age)

總結(jié) 

到此這篇關(guān)于JavaScript獲取URL中參數(shù)值的四種方法的文章就介紹到這了,更多相關(guān)JS獲取URL參數(shù)值內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論

南涧| 宁津县| 温宿县| 广河县| 抚宁县| 垦利县| 县级市| 专栏| 井研县| 彭水| 修文县| 襄垣县| 闽清县| 三原县| 建湖县| 荣成市| 华宁县| 遵义市| 鲁甸县| 元江| 达日县| 乌恰县| 长岛县| 石嘴山市| 广东省| 岗巴县| 垫江县| 永胜县| 荔浦县| 海伦市| 会同县| 南漳县| 福安市| 聊城市| 梅河口市| 岗巴县| 浠水县| 吉林市| 会同县| 武强县| 合川市|