GET query string parameters πββοΈ

A utility function to get the value of any query string parameter
We all know that the query string parameters are available for us through window.location (JavaScript Window Location Object). But query string usually turns up as a string and has to be parsed to get the necessary attribute out. There is an easy way through a utility function given below, this can be included in any web deployment:
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\"\\ "\\$&"amp;"amp;");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
// Usage for query string: ?sith=vader
var foo = getParameterByName('sith'); // "vader"
Happy Grizzly π» Coding!

Related Posts

JavaScript Promises: Promise.all vs Promise.allSettled vs Promise.race vs Promise.any
Ever wanted to be a Promises whizz. There are a few tricks you can learn to become that through the use of promise static methods for handling an array of promises in JavaScript

What's New in Node.js 24 (And How to Upgrade Your Codebase Smoothly)
Node.js 24 is here with game-changing features like V8 13.6, Float16Array, explicit resource management, WebAssembly Memory64, and npm 11. Learn what's new and how to upgrade smoothly.
Use Hook in React 18
This blog post focuses on the new experimental feature in React 18 called the use hook. It explains how the use hook can be used to create custom hooks that can be reused across different components, simplifying state management and making code more modular.