In a URL, query string values often provide information about the request, like parameters for a search or the ID of an object you're using. If any of the business or request logic is handled in the frontend, it's important to know how to retrieve the query string values from the URL. There are a number of ways to achieve this, a few of which we'll see here.
URLSearchParams
The URLSearchParams
interface is supported by all major browser versions except IE 11. It works by parsing the query string of a URL and providing a way to access the values. For example:
let params = new URLSearchParams('q=node&page=2');
params.get('q'); // 'node'
params.get('page'); // '2'
One of the downsides of this interface is that you must pass it only the query string of a URL. If you're working with the current browser URL, that's easy to do since you can just pass window.location.search
. If you're working with any other URL, you'll need to parse out and pass the query string separately.
To parse the query parameters into an object, use URL.searchParams
's .entries()
method, which returns an Iterator
of key/value pairs, and Object.fromEntries
to convert it into an object.
let params = new URLSearchParams('q=node&page=2');
let entries = params.entries();
Object.fromEntries(entries); // {q: 'node', page: '2'}
URL Object
The URL
API is also supported by all major browser versions except IE 11. It offers a more flexible way to parse URLs, and it also provides a way to access the query string values. For example:
const url = new URL('https://stackabuse.com/search?q=node&page=2');
const searchParams = url.searchParams;
searchParams.get('q'); // 'node'
searchParams.get('page'); // '2'
url.searchParams
is the same type of instance object returned by URLSearchParams
.
The url
object above also has all parts of the URL broken out into its parts. For example:
url.href; // 'https://stackabuse.com/search?q=node&page=2'
url.origin; // 'https://stackabuse.com'
url.protocol; // 'https:'
url.host; // 'stackabuse.com'
url.hostname; // 'stackabuse.com'
url.port; // ''
url.pathname; // '/search'
url.search; // '?q=node&page=2'
url.hash; // ''
Pure JavaScript
If for any reason you're not able to access the APIs above or want to have more control over the parsing, you can use the following code to parse the query string into an object.
function getQueryParams(url) {
const paramArr = url.slice(url.indexOf('?') + 1).split('&');
const params = {};
paramArr.map(param => {
const [key, val] = param.split('=');
params[key] = decodeURIComponent(val);
})
return params;
}
Note: There are many ways to parse query params in plain JS, some more complicated (and robust) than others. This is just one way, and was adapted from this gist.
We can then use this plain JS function to parse a single query param into a string:
getQueryParams('https://stackabuse.com/search?q=node&page=2')
// { q: 'node', page: '2' }