Is there a plugin-free way to retrieve query string values in JavaScript (without using jQuery)?
If so, how can I do that? And if not, is there a reliable plugin available to help with JavaScript get query string tasks?
Is there a plugin-free way to retrieve query string values in JavaScript (without using jQuery)?
If so, how can I do that? And if not, is there a reliable plugin available to help with JavaScript get query string tasks?
If you’re in a modern browser environment (which most of us are these days), this is the best way:
const urlParams = new URLSearchParams(window.location.search);
const value = urlParams.get('yourKey');
console.log(value);
It’s concise, readable, and natively supported in all major browsers.
If you’re supporting older environments or just want to avoid any dependencies, you can use:
function getQueryParam(key) {
const query = window.location.search.substring(1);
const pairs = query.split('&');
for (let i = 0; i < pairs.length; i++) {
const [k, v] = pairs[i].split('=');
if (decodeURIComponent(k) === key) {
return decodeURIComponent(v || '');
}
}
return null;
}
console.log(getQueryParam('yourKey'));
It is a bit verbose, but works even on legacy browsers.
If you’re already using Lodash or query-string, they can help too:
npm install query-string
import queryString from 'query-string';
const params = queryString.parse(window.location.search);
console.log(params.yourKey);
It is handy when you’re in a larger project and don’t mind using a lightweight lib.