1

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?

2

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.