ChatGPT解决这个技术问题 Extra ChatGPT

Redirecting to a relative URL in JavaScript

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?


K
Kobi

You can do a relative redirect:

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

or

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

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.
I found using window.location.href = '../' redirected to the root of the site and not "one level up" as expected. When the current page is "www.example.com/customers/list" I needed to use './'. I guess this is because "list" is not considered as a directory level.
@MarcusCunningham, in your example, the directory is /customers/ - so "one level up" is www.example.com/. Now if your example URL was www.example.com/customers/list/ - it would redirect you to www.example.com/customers/
y
ygrichman

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.


My browser barks when I go location.path and it seems only to recognize location.pathname. Hints?
location.path is incorrect, it should be location.hostname. I've added an edit to the post to fix this.
S
Shaun Luttin

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

window.location.assign("../"); // one level up

window.location.assign("/path"); // relative to domain


C
Chris Ballance

redirect to ../


If your app is hosted in a sub-uri and the app doesn't know the sub-uri path. If you are at your apps root and you do ../ the app won't know how to get back to its root. For example, the same app is hosted at example.com/myapp and other.example.com/app2
K
Kornel

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

.. means parent directory.


That requires a click or some other user-initiated navigation.
T
Timo Tijhof

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'

K
Kamil Kiełczewski

try following js code

location = '..'