Building a Query String
Not too long ago, in order to build a query string we had to do messy string concatenation (although it got much better with template literals) or rely on a library. Now, we can use the
let qs = new URLSearchParams(); qs.append('start', 'now-2m'); qs.append('end', 'now'); qs.toString(); // 'start=now-2m&end=now'
Parsing a Query String
Now let’s say we have a URL and we need to manually parse the query string. Instead of manually parsing the URL string, we can use the
let url = new URL('https://mysite.com/results?page=1&page-size=10'); let qs = url.searchParams; qs.get('page'); // 1 qs.get('page-size'); // '10'
searchParams property on a
URL instance is an instance of
One last thing to mention is browser support, which is pretty good for both of these classes. Check out their support on Can I use.
Disclaimer: Any viewpoints and opinions expressed in this article are those of David Tang and do not reflect those of my employer or any of my colleagues.