You are here:Home»KB»Programming»Javascript»Redirecting to a relative URL in JavaScript
Wednesday, 12 September 2012 00:00

Redirecting to a relative URL in JavaScript

Written by

I have a problem: I want to redirect via JavaScript to a directory above.


You can do a relative redirect:

{code}document.location.href = '../'; //one level up{/code}Or{code}document.location.href = '/path'; //relative to domain{/code}

  • see why you should use window.location.replace stackoverflow.com/questions/503093/…
  • When you want to simulate a link, you should use window.location.href. You should only use window.location.replace when you want to simulate an http redirect (thus not generating a history item).
  • By the way, document.location was intended as a read-only property. It is safer to use window.location. See this question.
  • If you use location.path 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.
Read 6885 times Last modified on Wednesday, 12 November 2014 23:23