How to usewindow.location.replace in Javascript

The replace function is used to navigate to a new URL without adding a new record to the history.

Syntax:

// Redirect to another page using replace
window.location.replace('https://www.example.com');

Example: This example shows the use of the window.location.replace which is used to load another page in JavaScript.

HTML




<!DOCTYPE html>
<html>
<body>
    <button onclick="replaceLocation()">
        Replace current webpage
    </button>
    <script>
        function replaceLocation() {
 
            // Replace the current location
            // with new location
            let newloc = "https://www.w3wiki.org/";
            window.location.replace(newloc);
        }
    </script>
</body>
</html>


Output:

How can a page be forced to load another page in JavaScript ?

In JavaScript, you can force a page to load another page by using the window.location object. There are a few methods to achieve this. To force a page to load another page in JavaScript, we have multiple approaches:

Below are the approaches used to force a page to load another page in JavaScript:

Table of Content

  • Using window.location.replace
  • Using window.location.assign Property

Similar Reads

Approach 1: Using window.location.replace

The replace function is used to navigate to a new URL without adding a new record to the history....

Approach 2: Using window.location.assign Property

...