There are so many scenarios where we want to redirect from the current webpage to a URL that is in the same domain or sometimes on another domain.
This can be redirected to a web page after login or registration.
Javascript provides a few different ways through which we can redirect to a different URL or a webpage.
Let's see these different methods one by one.
Redirect To Another Webpage Using window.location.href
Javascript provides us the location.href property on the window object.
Syntax for location.href method:
window.location.href = "REDIRECT_TO_THIS_URL";
Example:
window.location.href = "REDIRECT_TO_THIS_URL";
// Website is redirected to Google as soon
// as the website is loaded
Redirect To Another Webpage URL Using location.replace Method
This is a method available on the location property of the window object. The location.replace method takes a string or a URL as the only parameter of this method. This method returns a void.
Syntax for location.replace method:
window.location.replace("REDIRECT_TO_THIS_URL");
Example:
window.location.replace("https://google.com");
// Website is redirected to Google as soon
// as the website is loaded
Redirect To Another Webpage Using location.assign Method
This is another method available on the location property on the window object. The location.assign method takes a string or a URL similar to the location.replace method. This method returns a void.
Syntax for location.assign method:
window.location.href = "REDIRECT_TO_THIS_URL";
Example:
window.location.assign("https://google.com");
// Website is redirected to Google as soon
// as the website is loaded