Adding a parameter to the URL with JavaScript
Add a query parameter in a snap with this code snippet:
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
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()
:
Updating parameters in existing URLs
For those times when you're wrestling with an existing URL or the current location:
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:
Query string manipulation with regex
When speed matters (and when doesn't it?), regular expressions cut to the chase:
Reading the current query string
Need the query string for the current page? window.location.search
has you covered:
Proper escapement handling
Escape special characters with the escape()
function:
Was this article helpful?