開發項目的過程中,可能需要解析和生成相應的URL,使用URLSearchParams可以更快的去生成或者解析。
一、添加URLSearchParams
首先需要npm install個url-search-params-polyfill包
npm install url-search-params-polyfill --save
添加完成之后,將其引入到項目中。
import 'url-search-params-polyfill';
二、使用URLSearchParams
1、設置參數set
set的格式為set(參數名,值),設置參數字符串以及URL代碼如下
let search = new URLSearchParams()
search.set('test', '測試set')
search.set('type', '1')
let searchUrl = new URLSearchParams(window.location.href)
searchUrl.set('urlTest', '測試set')
searchUrl.set('urlType', '2')
console.log('輸出結果:', search.toString()) //輸出結果: test=%E6%B5%8B%E8%AF%95set&type=1
console.log('URL輸出結果:', searchUrl.toString()) //URL輸出結果: http%3A%2F%2Flocalhost%3A3000%2F=&urlTest=%E6%B5%8B%E8%AF%95set&urlType=2
2、獲取參數值get
get的格式為get(參數名),代碼如下
console.log(search.get('test')) //輸出結果:測試set
console.log(searchUrl.get('urlType')) //URL輸出結果:2
3、判斷是否存在某參數has
has的格式為has(參數名),返回的是boolean類型,代碼如下
console.log(search.has('type')) //輸出結果:true
console.log(searchUrl.has('test')) //URL輸出結果:false
4、append和getAll
在開發過程中,可能需要使用url傳遞一個數組參數,比如http://localhost:3000/?arr=[1,2,3],但是在推薦的形式是:http://localhost:3000/?arr=1&&arr=2&&arr=3,這種情況就可以使用append來添加相同的參數,使用getAll來獲取這個參數,獲取后自動轉化為數組類型。
append的格式為append(參數名,值),getAll的格式為getAll(參數名),具體代碼如下
search.append('type', '10')
searchUrl.append('urlType', '20')
console.log(search.getAll('type')) //輸出結果:["1", "10"]
console.log(searchUrl.getAll('urlType')) //URL輸出結果:["2", "20"]
常用的大概就是這幾個,還有delete,sort,foreach,keys,values,for of等,具體的可以參考一下原文https://www.npmjs.com/package/url-search-params-polyfill。