Window Location replace() JavaScript Tutorial

In this section, we will learn what the location replace() method is and how to use it in JavaScript.

JavaScript Location replace() Method:

The `replace()` method takes a URL and loads the content of that URL in the current browser window.

Basically, this method is a way of programmatically calling another external resource and load it in the current browser window to replace the currently loaded document.

There’s another method named `assign()` that does the same work, but here’s the difference:

  • Via the `assign()` method, after the target URL is loaded on the browser, we can hit the back button to move back to the previously loaded page.
  • But when using the `replace()` method, after loading the new document, we can’t move back to the previous URL via the back button. Basically, the `replace()` method will replace the last URL in the history of the browser with a new one. So the last one will be cleared from the history of the browser window.

Location replace() Method Syntax:

location.replace(newURL)

JavaScript Location replace() Parameter:

This method takes one argument and that is the URL of a document that we want to load on the current browser window.

JavaScript Location replace() Return Value:

The method does not return a value.

Example: JavaScript location redirect

See the Pen JavaScript location redirect by Omid Dehghan (@odchan1) on CodePen.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies