xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

js 解析 URL query 参数 All In One

js 解析 URL query 参数 All In One

const url = new URL('https://www.xgqfrms.xyz/index.html?date=2022-03-20');
const searchParams = new URLSearchParams(url.search);

for (let param of url.searchParams) {
    console.log('param =', param);
}
// param = (2) ['date', '2022-03-20']

demo

const url = new URL('https://www.xgqfrms.xyz/index.html?date=2022-03-20');

url;
/*
URL {origin: 'https://www.xgqfrms.xyz', protocol: 'https:', username: '', password: '', host: 'www.xgqfrms.xyz', …}hash: ""host: "www.xgqfrms.xyz"hostname: "www.xgqfrms.xyz"href: "https://www.xgqfrms.xyz/index.html?date=2022-03-20"origin: "https://www.xgqfrms.xyz"password: ""pathname: "/index.html"port: ""protocol: "https:"search: "?date=2022-03-20"searchParams: URLSearchParams[[Prototype]]: URLSearchParamsappend: ƒ append()delete: ƒ delete()entries: ƒ entries()forEach: ƒ forEach()get: ƒ ()getAll: ƒ getAll()has: ƒ has()keys: ƒ keys()set: ƒ ()sort: ƒ sort()toString: ƒ toString()values: ƒ values()constructor: ƒ URLSearchParams()Symbol(Symbol.iterator): ƒ entries()Symbol(Symbol.toStringTag): "URLSearchParams"[[Prototype]]: Objectusername: ""[[Prototype]]: URL
*/

url.searchParams;
// URLSearchParams {}

url.searchParams.entries();
// Iterator {}[[Prototype]]: Iterator
for (let param of url.searchParams) {
    console.log('param =', param);
}
// param = (2) ['date', '2022-03-20']



API

https://developer.mozilla.org/zh-CN/docs/Web/API/Location/search

URLSearchParams

let params = new URLSearchParams(document.location.search);
let name = params.get("name"); 
// is the string "eric"
let age = parseInt(params.get("age"), 10); 
// is the number 18

https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/get#examples

searchParams

let params = (new URL(document.location)).searchParams;
let name = params.get('name'); 
// is the string "eric".
let age = parseInt(params.get('age')); 
// is the number 18

https://developer.mozilla.org/en-US/docs/Web/API/URL/searchParams#examples

refs

https://www.cnblogs.com/xgqfrms/p/16031416.html



©xgqfrms 2012-2020

www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2021-04-09 12:12  xgqfrms  阅读(940)  评论(2编辑  收藏  举报