JavaScript獲取URL中參數(shù)值的四種方法
方法1:現(xiàn)代瀏覽器都支持 URL 和 URLSearchParams 對象,可以很方便地從URL中提取參數(shù)
// 假設(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
}
// 假設(shè)當前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;
}, {});
}
// 假設(shè)當前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è)當前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)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
用JavaScript實現(xiàn)瀏覽器截圖功能的全過程
在Web開發(fā)中實現(xiàn)網(wǎng)頁截圖功能可以幫助我們保存網(wǎng)頁內(nèi)容、生成海報、制作截圖分享等,這篇文章主要介紹了用JavaScript實現(xiàn)瀏覽器截圖功能的相關(guān)資料,文中通過代碼介紹的非常詳細,需要的朋友可以參考下2025-07-07
JavaScript無提示關(guān)閉窗口(兼容IE/Firefox/Chrome)
JavaScript無提示關(guān)閉當前頁面窗口,兼容IE/Firefox/Chrome (Close the current page window without confirm by JavaScript, support all browsers)2008-11-11
Object的相關(guān)方法 和 js遍歷對象的常用方法總結(jié)
這篇文章主要介紹了Object的相關(guān)方法 和 js遍歷對象的常用方法,結(jié)合實例形式總結(jié)分析了Object對象操作的操作方法與js遍歷的三種常用方法,需要的朋友可以參考下2023-05-05
Bun運行時是新一代高性能JavaScript/TypeScript運行時
Bun由Jarred Sumner創(chuàng)建,是一款新興的JavaScript和TypeScript運行時,旨在比Node.js和Deno提供更高性能和快速啟動,Bun使用Zig語言編寫,內(nèi)置包管理并支持Node.js大部分API,適用于高并發(fā)API服務(wù)和快速構(gòu)建工具2024-11-11

