亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

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

 更新時(shí)間:2025年04月01日 10:35:43   作者:夕陽(yáng)_醉了  
在前端開(kāi)發(fā)中,處理URL參數(shù)是一個(gè)常見(jiàn)的任務(wù),尤其是在沒(méi)有框架支持的情況下,這篇文章主要介紹了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

可以通過(guò) 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ù),此方法比較簡(jiǎn)單。

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)論