Redirecting to a relative URL in JavaScript

Redirecting to a relative URL in JavaScript

You can do a relative redirect:

window.location.href = ../; //one level up

or

window.location.href = /path; //relative to domain

If you use location.hostname you will get your domain.com part. Then location.pathname will give you /path/folder. I would split location.pathname by / and reassemble the URL. But unless you need the querystring, you can just redirect to .. to go a directory above.

Redirecting to a relative URL in JavaScript

https://developer.mozilla.org/en-US/docs/Web/API/Location/assign

  • window.location.assign(../); // one level up
  • window.location.assign(/path); // relative to domain

Leave a Reply

Your email address will not be published.