Home > Web Front-end > JS Tutorial > How Can I Modify URL Parameters and Set Defaults in JavaScript?

How Can I Modify URL Parameters and Set Defaults in JavaScript?

DDD
Release: 2024-11-17 22:22:01
Original
944 people have browsed it

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);
Copy after login

The updateURLParameter() function takes three parameters:

  • url: The original URL
  • param: The parameter to be modified
  • paramVal: The new value for the parameter

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);
}
Copy after login

Example URL

The provided URL:

site.fwx?position=1&archiveid=5000&columns=5&sorting=ModifiedTimeAsc
Copy after login

can be modified to:

site.fwx?position=1&archiveid=5000&columns=5&rows=10&sorting=ModifiedTimeAsc
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template