0

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?

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
kodfire
  • 1,612
  • 3
  • 18
  • 57
  • 1
    Read the documentation: [`URL`](//developer.mozilla.org/en/docs/Web/API/URL), [`URLSearchParams`](//developer.mozilla.org/en/docs/Web/API/URLSearchParams). – Sebastian Simon Jan 30 '23 at 10:46
  • Does this answer your question? [URLSearchParams does not return the same string as found in a URL's parameters](https://stackoverflow.com/questions/45516070/urlsearchparams-does-not-return-the-same-string-as-found-in-a-urls-parameters) – 0stone0 Jan 30 '23 at 10:47

1 Answers1

4

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'))
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335