Reputation: 4323
I have two different levels within my site, but each have a similar structure. For example:
http://example.com/demo/insights.html
and
http://example.com/demo/complete/insights.html
What I'd like to do is add a link/button that the user can click to go up or down a level depending on where they are. The last part of the URL (e.g., insights.html) would stay the same. It's just whether or not the directory would change up or down.
So, if I'm on http://example.com/demo/insights.html, there would be a button to get to http://example.com/demo/complete/insights.html. If I was on http://example.com/demo/complete/insights.html then there'd be a button to get to http://example.com/demo/insights.html.
I have a lot of pages like this, but I'd like to avoid hand-coding links on every page. I'm looking for something using javascript/jquery that will evaluate the directory level and the last part of the URL and redirect accordingly.
Any insights would be appreciated.
Upvotes: 2
Views: 703
Reputation: 13006
One way to do this is to count slashes:
var link = window.location.href;
var deep = link.match(/\//g).length - 3;
var chunks = link.split(/\//);
if (deep) { // level 2
link = chunks[0] + '//' + chunks[2] + '/' + chunks[4]; // get rid of one level (chunks[3])
} else { // level 1
link = chunks[0] + '//' + chunks[2] + '/extra-level/' + chunks[3]; // add a level
}
Upvotes: 1
Reputation: 65
You can use this:
location.assign('../'+location.pathname.substring(location.pathname.lastIndexOf("/") + 1))
Upvotes: 0
Reputation: 7490
window.location.href
will give you the url of the page you are on, from there its just a matter of splitting split()
the location and add/remove the required url substring
you can then add the new url into a common 'a' tag's href property on the page
As a rough example
var loc = window.location.href,
someSplits = loc.split("http://example.com/demo/"),
//you can do better reg ex, this is just quick
page = someSplits[1]; // this will give you the remaining url
// OR just replace the part you dont want
var loc = window.location.href,
page = loc.replace('http://example.com/demo/', '');
// this will give you the remaining url
Upvotes: 1