Redirecting to a relative URL in JavaScript

user199337 picture user199337 · Oct 31, 2009 · Viewed 512.9k times · Source

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

location.href = (location.href).substr(0, (location.href).lastIndexOf('folder'));

The URL looks like this:

example.com/path/folder/index.php?file=abc&test=123&lol=cool

The redirect affect just this:

example.com/path/&test=123&lol=cool

But want to have this:

example.com/path/

How could I do that?

Answer

Kobi picture Kobi · Oct 31, 2009

You can do a relative redirect:

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

or

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