Redirect your webpage using JavaScript

I recently moved my website from another domain to this one. I need to route the users from the old to this without much effort. So I decided to write a simple JavaScript which redirect from one page to another.

If you want the solution right away, copy and paste the below.

<script type="text/javascript">
  var timer = setTimeout(function() {
       window.location.replace('' + window.location.pathname);
  }, 3000);

The window.location object can be used to get the current page address and redirect to a new page. In the above script, replace method of the location interface replaces the current resource with one which we provided.

Also I need to redirect to exact page in the new website, for the same we can use the window.location.pathname which returns the path and filename of the current page.

If you want to dive more on Window Location object read the below.

window.location properties:
  • returns the domain name and port number of the web host.
  • window.location.hostname returns the domain name of the web host.
  • window.location.href returns the URL of the current page.
  • window.location.origin returns the protocol, hostname and port number of the URL.
  • window.location.pathname returns the path and filename of the current page.
  • window.location.port returns the port number of the URL. If the website is using default ports, it will omit the port number and display nothing.
  • window.location.protocol returns the web protocol used (http: or https:).
  • returns the query string of the URL.
window.location methods:
  • window.location.assign() loads a new document.
  • window.location.reload() Reloads the current document.
  • window.location.replace() Replace the current URL with new one.


Let assume for the below url 




// /blog/2023/06/get-current-url-javascript/ 


// https:

Read More