Reputation: 44293
I have this URL http://www.something.com/category
and
top.location.href.substr(0, top.location.href.lastIndexOf("/") );
returns http://www.something.com
However if I have the URL http://www.something.com/category/something
how can I again retrieve http://www.something.com
by removing the 2nd last appearance of "/" …
Any idea? I know there is stuff like top.location.origin
. I need a way to cut the last two "slashes" off!
Upvotes: 0
Views: 271
Reputation: 348972
Since you're working with the location
object, use:
location.protocol + '//' + location.host + '/';
// On this page, it shows: http://stackoverflow.com/
// Include pathname:
location.protocol + '//' + location.host + location.pathname + '/';
For your own solution, you can add +1
to the second argument:
top.location.href.substr(0, top.location.href.lastIndexOf("/")+1 );
^^ Hi Plus One!
Response to updated question (see OPs comments):
var href = top.location.href.replace(/(\/[^\/]+){2}\/?$/, '');
Upvotes: 1
Reputation: 754565
Instead of going backwards which can have a variable number of indexes, why not go forwards where you know there will only be 2 ahead of it?
var url = top.location.href;
var index1 = url.indexOf('/');
var index3 = url.indexOf('/', index1 + 2);
var final = url.substr(0, index3);
Upvotes: 0