JavaScript location replace() method

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:

  1. 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);
  1. 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);
  1. 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

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: