Velvet Star Monitor

Standout celebrity highlights with iconic style.

updates

Redirecting to a relative URL in JavaScript

Writer Matthew Barrera

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:

The redirect affect just this:

But want to have this:

How can I do it?

0

7 Answers

You can do a relative redirect:

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

or

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

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.

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

redirect to ../

1

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

.. means parent directory.

1

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'

try following js code

location = '..'