JavaScript · Senior · Question 44 of 75
What's the right way to build a query string from a params object?
- ✓Correct answer: With
new URLSearchParams(params).toString() - 2Concatenate strings by hand:
'?q=' + q + '&page=' + page - 3With
JSON.stringify(params), passing the result as the query
Explanation
URLSearchParams correctly encodes spaces, non-ASCII characters and special characters like &, which would break the request or allow parameter tampering with manual concatenation. The URL object lets you work with the whole address: url.searchParams.set('page', 2).