Explain Codes LogoExplain Codes Logo

How to retrieve GET parameters from JavaScript

javascript
prompt-engineering
functions
callbacks
Alex KataevbyAlex Kataev·Oct 7, 2024
TLDR

Simple way to extract GET parameters using URLSearchParams:

let params = new URLSearchParams(document.location.search); let value = params.get('key'); // 'key' is your parameter name... easy, right?

We're fetching the value of 'key' from the URL's query string. Voilà!

Needle in the haystack: complex queries

If you're dealing with a URL with an intricate query string, you'll need every tool in your JavaScript belt:

let searchParams = window.location.search.substr(1).split('&'); // Splits and looks for '&' in the query let queryParams = {}; for (let param of searchParams) { let [key, value] = param.split('='); // Splits again using '=' queryParams[key] = decodeURIComponent(value || ""); // Decode and store each value, '' if undefined }

This transforms our query string into an object. Time to play detective 🕵️‍♀️ and decode the parameters.

Keeping safe: security concerns

As the proverb (probably) goes, "Trust no URL":

if(queryParams.hasOwnProperty('userInput')) { // Check for 'userInput' paramater let userInput = queryParams['userInput']; // Get its value // Remember to sanitize userInput before using it, there are real monsters out here! }

Always sanitize input to protect your application from evil (malicious) attempts.

Taking things in your own hands: parsing manually

Sometimes, you've just got to do it yourself:

function transformToAssocArray(query) { if (!query) return {}; // Nothing to see here... return query.split('&').reduce((params, param) => { // Getting close... let [key, value] = param.split('='); // Voila! params[key] = value ? decodeURIComponent(value.replace('+', ' ')) : ''; // Handle '+' in query strings too return params; }, {}); } let queryParams = transformToAssocArray(window.location.search.substr(1)); // '*.substr(1)' gets rid of '?'

This manual parsing provides graceful handling of empty or null query strings.

Growing your garden: adding and manipulating parameters

With URLSearchParams: adding new buds🌱 and trimming the old branches🍃 is a joy ride:

params.append('newParam', 'newValue'); // Plants a 'newParam' with 'newValue' params.set('existingParam', 'updatedValue'); // Gives a makeover to 'existingParam'

In-depth journey: utilizing window.location object

For greater adventures, you might need to trek through various parts of window.location:

let currentUrl = window.location.href; // Your current landmark let pathname = window.location.pathname; // Path to the dungeon 🏰 let hash = window.location.hash; // Some treasure hidden away

Overcome the programming challenges and extract as much information as you can!