简体   繁体   中英

Why the url first parameter is not being considered in Javascript?

 const url = new URLSearchParams('https://example.com?q1=1&q2=2'); console.log(url.has('q3')) // returns false as expected console.log(url.has('q2')) // returns true as expected console.log(url.has('q1')) // returns false as NOT expected

Why it happens?

The URLSearchParams constructor, if passed a string, expects that string to be a query string and not a complete URL.

q1 doesn't appear because your first parameter is https://example.com?q1 .

 const url = new URLSearchParams('https://example.com?q1=1&q2=2'); console.log([...url.entries()]);

Use the URL constructor if you want to parse a complete URL.

 const url = new URL('https://example.com?q1=1&q2=2'); console.log(url.searchParams.has('q3')) console.log(url.searchParams.has('q2')) console.log(url.searchParams.has('q1'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM