sollrei / mini-note

https://github.com/GcFETeam/10min-quick-share/issues
3 stars 1 forks source link

获取url参数 #32

Open sollrei opened 4 years ago

sollrei commented 4 years ago

示例地址 https://example.com/?product=shirt&color=blue&newuser&size=m

const queryString = window.location.search;
// ?product=shirt&color=blue&newuser&size=m

const urlParams = new URLSearchParams(queryString);

URLSearchParams IE不支持

image

const product = urlParams.get('product')
console.log(product);
// "shirt"

const newUser = urlParams.get('newuser')
console.log(newUser);
// ""

console.log(urlParams.has('product'));
// true

console.log(urlParams.has('paymentmethod'));
// false

console.log(urlParams.getAll('size'));
// [ 'm' ]

for (const key of urlParams.keys()) console.log(key);
// product, color, newuser, size
sollrei commented 4 years ago

参考: https://www.sitepoint.com/get-url-parameters-with-javascript/