js獲取url參數(shù)值的幾種方式詳解
方法一:
采用正則表達式獲取地址欄參數(shù) (代碼簡潔,重點正則)
function getQueryString(name) {
let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
let r = window.location.search.substr(1).match(reg);
if (r != null) {
return unescape(r[2]);
};
return null;
}調用方法
let 參數(shù)1 = GetQueryString("參數(shù)名1"));
方法二:
split拆分法 (代碼較復雜,較易理解)
function GetRequest() {
const url = location.search; //獲取url中"?"符后的字串
let theRequest = new Object();
if (url.indexOf("?") != -1) {
let str = url.substr(1);
strs = str.split("&");
for(let i = 0; i < strs.length; i ++) {
theRequest[strs[i].split("=")[0]]=unescape(strs[i].split("=")[1]);
}
}
return theRequest;
}調用方法
let Request = new Object();
Request = GetRequest();
var 參數(shù)1,參數(shù)2 ...;
參數(shù)1 = Request['參數(shù)1'];
參數(shù)2 = Request['參數(shù)2'];
參數(shù)... = Request['參數(shù)...'];
方法三:split拆分法(易于理解,代碼中規(guī))
function getQueryVariable(variable){
let query = window.location.search.substring(1);
let vars = query.split("&");
for (let i=0;i<vars.length;i++) {
let pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
}調用方法
let 參數(shù)1 = getQueryVariable("參數(shù)名1");
補充URL知識
1、window.location.href(設置或獲取整個 URL 為字符串)
console.log(window.location.href)
打印結果:http://www.jianshu.com/search?q=123&page=1&type=note
2、window.location.protocol(設置或獲取 URL 的協(xié)議部分)
console.log(window.location.protocol)
打印結果:http:
3、window.location.host(設置或獲取 URL 的主機部分)
console.log(window.location.host)
打印結果:www.jianshu.com
4、window.location.port(設置或獲取與 URL 關聯(lián)的端口號碼)
console.log(window.location.port)
打印結果:空字符(如果采用默認的80端口(update:即使添加了:80),那么返回值并不是默認的80而是空字符)
5、window.location.pathname(設置或獲取與 URL 的路徑部分(就是文件地址))
console.log(window.location.pathname)
打印結果:/search
6、window.location.search(設置或獲取 href 屬性中跟在問號后面的部分)
console.log(window.location.search)
打印結果:?q=123&page=1&type=note
PS:獲得查詢(參數(shù))部分,除了給動態(tài)語言賦值以外,我們同樣可以給靜態(tài)頁面,并使用javascript來獲得相信應的參數(shù)值。
7、window.location.hash(設置或獲取 href 屬性中在井號“#”后面的分段)
console.log(window.location.hash)
打印結果:空字符(因為url中沒有)
以上就是js獲取url參數(shù)值的幾種方式詳解的詳細內容,更多關于js獲取url參數(shù)值的資料請關注腳本之家其它相關文章!
相關文章
JavaScript計算出現(xiàn)精度丟失問題的解決方法
Javascript作為一門大型編程語言,在日常開發(fā)中難免會涉及到大量的數(shù)學計算,然而,浮點數(shù)在計算過程中可能出現(xiàn)精度的問題,下面我們就來學習一下Javascript中高精度計算及其相關知識吧2023-11-11
Web前端JavaScript中findIndex方法使用示例
這篇文章主要介紹了Web前端JavaScript中findIndex方法使用的相關資料,findIndex()?返回第一個符合條件的數(shù)組子項的下標,找到符合條件的之后就不在繼續(xù)遍歷,需要的朋友可以參考下2025-08-08
JavaScript性能優(yōu)化之減少DOM操作全方位攻略指南
DOM操作是Web開發(fā)中最耗性能的操作之一,頻繁的DOM訪問和修改會導致瀏覽器不斷重繪和回流,嚴重影響頁面性能,下面我們就來看看JavaScript減少DOM操作的具體方法吧2025-12-12
javascript+ajax實現(xiàn)產(chǎn)品頁面加載信息
本文給大家分享的是使用javascript結合ajax實現(xiàn)產(chǎn)品頁面無刷新加載信息的代碼,非常的簡單實用,有需要的小伙伴可以參考下。2015-07-07

