Redirecting to a relative URL in JavaScript

JavascriptUrlRedirect

Javascript Problem Overview


My problem is that 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 can I do it?

Javascript Solutions


Solution 1 - Javascript

You can do a relative redirect:

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

or

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

Solution 2 - Javascript

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.

Solution 3 - 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

Solution 4 - Javascript

redirect to ../

Solution 5 - Javascript

<a href="..">no JS needed</a>

.. means parent directory.

Solution 6 - Javascript

I'm trying to redirect my current web site to other section on the same page, using JavaScript. This follow code work for me:

location.href='/otherSection'

Solution 7 - Javascript

try following js code

location = '..'

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser199337View Question on Stackoverflow
Solution 1 - JavascriptKobiView Answer on Stackoverflow
Solution 2 - JavascriptBobView Answer on Stackoverflow
Solution 3 - JavascriptShaun LuttinView Answer on Stackoverflow
Solution 4 - JavascriptChris BallanceView Answer on Stackoverflow
Solution 5 - JavascriptKornelView Answer on Stackoverflow
Solution 6 - JavascriptJorge Santos NeillView Answer on Stackoverflow
Solution 7 - JavascriptKamil KiełczewskiView Answer on Stackoverflow