欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

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

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

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

方法2:使用正則表達式

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

function getQueryParam(name) {
  const regex = new RegExp('[?&]' + name + '=([^&#]*)', 'i')
  const results = regex.exec(window.location.href)
  return results ? decodeURIComponent(results[1]) : null
}
// 假設當前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 方法手動拆分查詢參數(shù),并用 reduce 將其轉(zhuǎn)化為對象。

function getQueryParams() {    
    return window.location.search
    .substring(1) // 去掉 ?        
    .split('&') // 按 & 拆分       
    .reduce((params, param) => {            
        const [key, value] = param.split('=');            
        params[decodeURIComponent(key)] = decodeURIComponent(value || '');            
        return params;        
    }, {});
}
// 假設當前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 上構建自己的解析函數(shù),此方法比較簡單。

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

總結 

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

相關文章

最新評論