JavaScript location methods: href, replace, and assign differences explained

JavaScript provides developers with several methods for manipulating the current URL of a page. Three of the most commonly used methods are href, replace, and assign.

├Źndice
  1. href
  2. replace
  3. assign

href

The href method is used to get or set the entire URL of the current page. This method returns a string that contains the complete URL of the current page. To set the URL, simply assign a new URL to the href property.

let currentUrl = window.location.href;
window.location.href = "http://www.example.com";

replace

The replace method is used to replace the current URL with a new URL, without adding a new entry to the browser's history. This means that the user cannot use the back button to return to the previous page. To use this method, simply call the replace method and pass in the new URL.

window.location.replace("http://www.example.com");

assign

The assign method is used to load a new document. This method adds a new entry to the browser's history, so the user can use the back button to return to the previous page. To use this method, simply call the assign method and pass in the new URL.

window.location.assign("http://www.example.com");

In summary, the href method is used to get or set the entire URL of the current page, while the replace method is used to replace the current URL with a new URL, without adding a new entry to the browser's history. The assign method is used to load a new document and add a new entry to the browser's history.

Understanding the differences between these methods is crucial for developers who need to manipulate the URL of a page. Whether you need to set the URL, replace it, or load a new document, there is a JavaScript method that can help you achieve your goal.

Click to rate this post!
[Total: 0 Average: 0]

Related posts

Leave a Reply

Your email address will not be published. Required fields are marked *

Go up

Below we inform you of the use we make of the data we collect while browsing our pages. You can change your preferences at any time by accessing the link to the Privacy Area that you will find at the bottom of our main page. More Information