Sky
Sky

Reputation: 4370

Redirect to previous ROUTE in Javascript

Suppose I'm on this page:

http://example.com/users/BECCA/edit/advanced

I want to redirect the user to:

http://example.com/users/BECCA/edit

How can I do this?

(I'm also familiar with window.history.back(); but my question is something else!)

Thanks.

Upvotes: 0

Views: 84

Answers (2)

Daniel.V
Daniel.V

Reputation: 2492

The first answer is right but just have one problem, it does't work for http://example.com/
So the better code should be this:

var url = location.href.split("/");
if(url.lenght == 3){
//the url is http://example.com/ do what ever you want
}
else{
     location.href=url.slice(0,-1).join("/");
}

Upvotes: 0

nicael
nicael

Reputation: 18995

  1. Split your current location into an array using delimiter /
  2. Remove the last object in this array
  3. Join the objects into string taking / as delimiter

location.href=location.href.split("/").slice(0,-1).join("/");

Upvotes: 1

Related Questions