1. 程式人生 > >獲取url的參數

獲取url的參數

ref 地址 return .html ram href bubuko url name

工作中封裝了一些通用的公共方法,最常見的就屬在url上拿參數了

現在用的是 getUrlParam2 方法


/** * 瀏覽器裏取參數 * @param name * @returns {*} */ export function getUrlParam(search, name) { const reg = new RegExp(`(^|&)${name}=([^&]*)(&|$)`, ‘i‘); const r = search.substr(1).match(reg); if (r != null) return decodeURI(r[2]); return null; }
/** * 瀏覽器裏取參數 * @param name * @returns {string} */ export function getUrlParam2(name) { let urlArr = window.location.href.split(‘?‘); if (urlArr.length < 2) { return ‘‘; } let tempArr = urlArr[1].split(‘&‘); for (let i = 0; i < tempArr.length; i++) { let item = tempArr[i].split(‘=‘); if (item[0].trim() == name) { return item[1]; } } return ‘‘; } 小擴展: 如何檢測 技術分享圖片

location.href 整個url地址

location.protocol 獲取協議

location.pathname 獲取地址

location.search 獲取?後面的參數

location.hash 獲取哈希

如:

http://www.baidu.com/class.html?aa=1&bb==2#id=123

location.href http://www.baidu.com/class.html?aa=1&bb==2#id=123

location.host www.baidu.com

location.protocol http://

location.pathname /class.htm

location.search ?aa=1&bb==2

location.hash #id=123

獲取url的參數