The JavaScript location replace() method is used to replace the current page with a new page. It takes one required argument: a string value representing the URL of the new page. It does not return any value.
Here are some examples of how the replace() method can be used in JavaScript code:
- To replace the current page with a new page, you can use the following code:
// define the URL of the new page
const url = 'http://www.example.com/';
// replace the current page with the new page
location.replace(url);
- To replace the current page with a new page and log a message to the console, you can use the following code:
// define the URL of the new page
const url = 'http://www.example.com/';
// replace the current page with the new page and log a message to the console
console.log('Redirecting to', url);
location.replace(url);
- To replace the current page with a new page and save the previous page in the history, you can use the following code:
// define the URL of the new page
const url = 'http://www.example.com/';
// save the current page in the history
history.pushState(null, null, location.href);
// replace the current page with the new page
location.replace(url);
Overall, the replace() method provides a convenient way to replace the current page with a new page. It can be useful for tasks such as redirecting to a different page or replacing the page without affecting the history, or for other operations that require replacing the current page.
Leave a Reply