Yogesh Chauhan's Blog

How to redirect or load a new document using JavaScript?

in JavaScript on March 14, 2021

Web APIs in JavaScript are really useful. One of the interfaces available is Location interface that has several properties and methods we can take advantage of.

We can use location.replace() or location.assign() method to redirect user to a new location.

Location replace() method in JavaScript

The replace() method simply replaces the current HTML document with a new one.

Location assign() method in JavaScript

The replace() method simply loads new HTML document in the browsing window.

What’s the difference between assign() and replace() methods in JavaScript?

The replace() method removes the URL of the current document from the browser’s document history. So, that the user can not go back using the “back” button in the browser. That way you can stop users from going back to the original document.

Which one should you use between assign() and replace() methods in JavaScript?

It depends on your requirements. If you want to give your users an option to go back to the original document, use the assign() method. If not, use the replace() method.

How to use assign() method in JavaScript?

The syntax is very simple:


where URL is a required string.

Use it like this:


How to use replace() method in JavaScript?

Same exact way as the assign() method.

The syntax is very simple:


where URL is a required string.

Use it like this:


Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Aug 15 Is PHP still good for back-end programming? #Aug 10 How to create a multisite network in WordPress? #Aug 3 How to create a circle that follows a cursor using JavaScript and CSS? #Aug 3 How to make a curtain slider using jQuery and CSS? #Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS?
You might also like these
How to add Google Static Map using ACF map field?WordPressWhat are Conditional Tags in WordPress?WordPressHow to define visibility for a property in PHP?PHPWhy do we need HAVING Clause in SQL?SQL/MySQLHow to create a full screen loader using CSS and JavaScript?CSSCheck if mixin is being called in a style rule or not in SCSSSCSS