Explain Codes LogoExplain Codes Logo

Adding a parameter to the URL with JavaScript

javascript
url-manipulation
ajax
url-search-params
Nikita BarsukovbyNikita Barsukov·Dec 8, 2024
TLDR

Add a query parameter in a snap with this code snippet:

let url = new URL('http://example.com'); url.searchParams.set('key', 'value'); // Replace 'key' & 'value' with your values - done faster than you can say "JavaScript"! console.log(url.href); // http://example.com?key=value

The URL constructor generates a URL object, which searchParams.set() then modifies, instantly inserting or updating a query parameter. Access the result directly with url.href.

Introducing URL modification with URLSearchParams

The URLSearchParams interface provides a set of methods to perform URL manipulation tasks with JavaScript. Used mainly in AJAX-driven applications, it allows URLs to change without needing a page reload.

Creating and updating parameters

let url = new URL('http://example.com'); // Set or update parameters url.searchParams.set('first', '1'); // Whats the best value? Number 1! url.searchParams.append('second', '2'); // Because sometimes, second place is all right too console.log(url.href); // http://example.com?first=1&second=2

The set() method inserts or updates existing parameters, while append() adds a new parameter even if one of the same name exists, enabling multiple values.

Encoding special characters

Protect your parameters from special characters by using encodeURIComponent():

let paramKey = encodeURIComponent('param/key'); // Makes sure param/key doesn't go rogue let paramValue = encodeURIComponent('value with spaces'); // Gives 'value with spaces' a space to exist url.searchParams.set(paramKey, paramValue);

Updating parameters in existing URLs

For those times when you're wrestling with an existing URL or the current location:

let currentUrl = new URL(window.location.href); currentUrl.searchParams.set('newParam', 'newValue'); // Adds a nice new shiny parameter history.pushState({}, '', currentUrl); // Updates URL without reloading - the ultimate stealth move

Browser compatibility

Always check browser support as some browsers, like Internet Explorer, don't support URLSearchParams.

Advanced URLSearchParams tricks

You're now about to enter the exciting - or terrifying - world of complex URL manipulations. It's a place where your code will need to be anything but basic. It's time to become a URLSearchParams Wizard!

Array parameters

When facing array parameters, handle them gracefully:

let arrayValues = ['value1', 'value2', 'value3']; // We're all about that array life arrayValues.forEach((value, index) => { url.searchParams.append(`arrayParam[${index}]`, value); });

Query string manipulation with regex

When speed matters (and when doesn't it?), regular expressions cut to the chase:

let queryString = currentUrl.search.replace(/(key=)[^&]+/, '$1newValue'); currentUrl.search = queryString; // Now it's regex to the rescue!

Reading the current query string

Need the query string for the current page? window.location.search has you covered:

let params = new URLSearchParams(window.location.search); let specificValue = params.get('key'); // Get 'key' if you dare!

Proper escapement handling

Escape special characters with the escape() function:

let safeValue = escape('This & That'); url.searchParams.set('query', safeValue); // Now 'This & That' is fit for web society