avaweb
在我們平常的javaweb開發(fā)中,前臺頁面經(jīng)常會用到獲取url中的參數(shù),大多數(shù)程序員可能直接
用window.location.href 獲取到當(dāng)前頁面的url,然后再用substring去截取字符串,這樣的話很麻煩。
當(dāng)然我上面所說的是在html的文件中,如果你是用的jsp的話,那就很簡單了。用el表達(dá)式我們可以很輕松的獲取url中的參數(shù):${param.paramName}
好了,言歸正傳,那如何在html中獲取url中的參數(shù)了?
我們可以單獨封裝一個函數(shù)來達(dá)到這個目的。以后只要是要獲取url的參數(shù),直接調(diào)用這個函數(shù)就可以了。
function get_param(name, url){
if(!url) url = window.location.href;
name = name.replace(/[\[\]]/g,"\$&");
var regex =newRegExp("[?&]"+ name +"(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if(!results) return null;
if(!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g," "));
}
我在后續(xù)的文章中,會分享更多更實用的開發(fā)小技巧給大家,希望大家多多關(guān)注!
const urlSearchParams = new URLSearchParams(window.location.search);
const queryParams = Object.fromEntries(urlSearchParams.entries());
console.log(queryParams);//成功轉(zhuǎn)換成對象
注意看url中的查詢值哦
const urlSearchParams = new URLSearchParams(window.location.search);
const value = urlSearchParams.get("a");
console.log(value);
拿來吧你
家好,我是大澈!
本文約 600+ 字,整篇閱讀約需 1 分鐘。
每日分享一段優(yōu)質(zhì)代碼片段。
今天分享一段優(yōu)質(zhì) JS 代碼片段,從而比以往更簡單的從 URL 中獲取查詢參數(shù)。
老規(guī)矩,先閱讀代碼片段并思考,再看代碼解析再思考,最后評論區(qū)留下你的見解!
const getQueryByName = (name) => {
const query = new URLSearchParams(location.search)
return decodeURIComponent(query.get(name))
}
// url: https://sunday.com/?name=fatfish&age=100
const name = getQueryByName('name') // fatfish
const age = getQueryByName('age') // 100
const gender = getQueryByName('gender') // null
分享原因
這段代碼通過 URLSearchParams 對象簡化了從 URL 中獲取查詢參數(shù)的過程。
通過這種方法,可以更方便地在 JavaScript 中解析和獲取 URL 查詢參數(shù),特別適用于處理需要從 URL 中提取參數(shù)的場景,比如讀取用戶在網(wǎng)頁中的輸入或搜索關(guān)鍵字等。
這是項目中一個很常見的操作,之前我們經(jīng)常會使用 正則表達(dá)式 或者 拆分字符串 來完成,現(xiàn)在有了更簡單的方式!
代碼解析
1. const query = new URLSearchParams(location.search);
創(chuàng)建 URLSearchParams 對象。
URLSearchParams 是 Web API 的一部分,用于操作 URL 的查詢字符串。
location.search 返回當(dāng)前 URL 的查詢字符串(例如 ?name=value&key=value)。
URLSearchParams 對象將其解析為一個可以操作的查詢參數(shù)對象。
2. decodeURIComponent(query.get(name));
query.get(name) 方法從查詢參數(shù)對象中獲取名稱為 name 的參數(shù)值。
decodeURIComponent 用于對參數(shù)值進(jìn)行解碼,以確保返回的值是一個人類可讀的字符串,避免 URL 編碼帶來的問題(例如 %20 代表空格)。
- end -
*請認(rèn)真填寫需求信息,我們會在24小時內(nèi)與您取得聯(lián)系。