In web development, it’s common to need to modify URLs dynamically. One such modification is adding or updating parameters in a URL. This can be particularly useful when working with AJAX calls or when you want to manipulate the current page’s URL without reloading the page. In this tutorial, we’ll explore how to achieve this using JavaScript.
Introduction to URL API
The URL
API and its associated URLSearchParams
object provide a modern and efficient way to work with URLs in JavaScript. The URL
object allows you to easily parse and manipulate URLs, while URLSearchParams
makes it straightforward to add, update, or remove query parameters from a URL.
Using URLSearchParams
To add or update a parameter in a URL using URLSearchParams
, follow these steps:
- Create a new
URL
object with the original URL. - Access its
searchParams
property, which returns aURLSearchParams
object. - Use methods like
append()
,set()
,get()
, ordelete()
to manipulate parameters.
Here’s an example that demonstrates how to add and update parameters:
// Original URL: http://example.com/path?a=1&b=2
const url = new URL('http://example.com/path?a=1&b=2');
// Add a new parameter 'c' with value 3
url.searchParams.append('c', 3);
console.log(url.href); // Output: http://example.com/path?a=1&b=2&c=3
// Update the existing parameter 'a'
url.searchParams.set('a', 10);
console.log(url.href); // Output: http://example.com/path?a=10&b=2&c=3
Manipulating Current Page URL
If you need to modify the current page’s URL, you can use window.location
object in conjunction with URLSearchParams
. Here’s how:
const urlParams = new URLSearchParams(window.location.search);
// Add a new parameter 'order' with value 'date'
urlParams.set('order', 'date');
// Update the current page's URL search parameters
window.location.search = urlParams;
Older Browsers and Workarounds
While URL
and URLSearchParams
APIs are widely supported, older browsers like Internet Explorer might not support them. For such cases, you can implement your own functions to parse and modify URLs using string manipulation techniques.
function insertParam(key, value) {
key = encodeURIComponent(key);
value = encodeURIComponent(value);
var kvp = document.location.search.substr(1).split('&');
let i = 0;
for (; i < kvp.length; i++) {
if (kvp[i].startsWith(key + '=')) {
let pair = kvp[i].split('=');
pair[1] = value;
kvp[i] = pair.join('=');
break;
}
}
if (i >= kvp.length) {
kvp[kvp.length] = [key, value].join('=');
}
// Update the page's URL search parameters
document.location.search = kvp.join('&');
}
Conclusion
Manipulating URLs and their parameters in JavaScript is a common requirement for web applications. The URL
API and URLSearchParams
object provide a clean and efficient way to achieve this, making it easier to add or update parameters without manually parsing the URL string. For scenarios where compatibility with older browsers is necessary, custom implementations can be used as workarounds.