Redirect to another page in JavaScript
During the execution of our code, we need to redirect to another page. There are many ways to redirect a web page to another web page in JavaScript. So today we will explain how we can easily redirect a page using JavaScript.
- Compare two dates in JavaScript
- Convert a String to a Number in JavaScript
- Replace all occurrences of a string in JavaScript
- Get Current Date & Time in JavaScript
- Round a Number to Decimal Points in JavaScript
Two ways to manage the redirection of web page
1. Javascript URL redirection
Using window.location
and window.location.href
we can redirect to another web page. window.location is an object that holds the information about the current location of the document and href is property of window.location, window.location.href is full url of current page. Both works the same but differences in their usage.
window.location = "https://www.codepremix.com/"
window.location.href = "https://www.codepremix.com/";
If you want to redirect to internal website page use:
window.location.href = "/category/javascript";
2. Using location object methods
- reload()
- replace()
- assign()
**1. reload()**reload() method used to refresh or reload the current page.
window.location.reload();
**2. replace()**replace() is the method of window.location object, it will replace the current document with a new one. It rewrites the current page in history, which may affect behaviour of back button.
window.location.replace('https://www.codepremix.com/');
**3. assign()**assign() method loads a new document in the browser window. This method different than replace() method because it rewrites the current page in history so when we click the back button, we go back to last visited page.
window.location.assign('https://www.codepremix.com/');
I hope you find this article helpful.
Thank you for reading. Happy Coding..!!