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
DDDOriginal
2024-11-17 22:22:01939browse

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:

  • 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);
}

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!

Statement:
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