Search code examples
javascriptquery-stringurl-parametersurlsearchparams

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?


Solution

  • 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'))