Parse and stringify URL query strings
Quick Answer
`URLSearchParams` is the built-in browser and Node.js API for parsing and building query strings — handling encoding, decoding, and repeated keys automatically.
1const parseQueryString = (url) => {
2 const params = new URLSearchParams(url.split('?')[1]);
3 return Object.fromEntries(params.entries());
4};
5
6const stringifyQueryString = (params) => {
7 return new URLSearchParams(params).toString();
8};URLSearchParams is the native browser and Node.js API for working with URL query strings. It handles encoding and decoding automatically, supports repeated keys, and integrates naturally with the URL API. These two helpers cover the most common operations: parsing a query string into an object and serialising an object back to a query string.
Use `params.getAll('key')` to retrieve all values for a repeated key (e.g. `?tag=js&tag=ts`). `Object.fromEntries` only returns the last value per key.
This free javascript code snippet for query string parser is production-ready and copy-paste friendly. Whether you are building a web app, API, or frontend interface, this intermediate-level example will help you implement query string parser quickly and correctly.
All snippets in the Snippetly library follow javascript best practices and are tested for real-world use. You can adapt this code to work with React, Vue, Node.js, or any project that uses javascript.
Organise your team's code snippets with Snippetly. Share knowledge and boost productivity across your organisation.