Home >Web Front-end >JS Tutorial >How Can I Modify URL Parameters and Set Defaults in JavaScript?
Altering URL Parameters and Defining Defaults with JavaScript
When working with URLs, it may be necessary to modify or add specific parameters to control the behavior of a web page. This can be achieved using JavaScript.
Modifying an Existing Parameter
To modify an existing parameter in the URL, such as changing the 'rows' value to 10, use the following code snippet:
var newURL = updateURLParameter(window.location.href, 'rows', 10);
The updateURLParameter() function takes three parameters:
Adding a Parameter if Not Present
In case the parameter doesn't exist in the original URL, you can add it using the same function:
if (!window.location.href.includes('rows')) { newURL = updateURLParameter(window.location.href, 'rows', 10); }
Example URL
The provided URL:
site.fwx?position=1&archiveid=5000&columns=5&sorting=ModifiedTimeAsc
can be modified to:
site.fwx?position=1&archiveid=5000&columns=5&rows=10&sorting=ModifiedTimeAsc
using the code above.
Additional Functionality
The provided code can also handle anchors in the URL, ensuring that they are preserved after parameter modification.
The above is the detailed content of How Can I Modify URL Parameters and Set Defaults in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!