Actually both your examples work the same. /stations/
and /stations/index.html
both get split into two strings; /stations/
has an empty string at the end. So length-2
would have worked. Where it wouldn't work would be /stations
, which is up a level. But that wouldn't normally be an issue because if stations
is a static directory, the web server will redirect the browser to /stations/
with the slash.
That won't happen if you're doing the routing yourself. If you're doing routing, it's not a good idea to index from the end of the list of path parts, are there might be any old rubbish there being passed as path-parameters, eg. /stations/region1/stationname2
. In this case you should be indexing from the start instead.
If the application can be mounted on a path other than a root you will need to tell JavaScript the path of that root, so it can work out how many slashes to skip. You'll probably also need to tell it for other purposes, for example if it creates any images on the fly it'll need to know the root to work out the directory to get images from.
var BASE= '/path-to/mysite';
var BASELEVEL= BASE.split('/').length;
...
var pagename= location.pathname.split('/')[BASELEVEL];
// '/path-to/mysite/stations/something' -> 'stations'
I'm using location.pathname
to extract only the path part of the URL, rather than trying to pick apart href
with string or regex methods, which would fail for query strings and fragment identifiers with /
in them.
(See also protocol
, host
, port
, search
, hash
for the other parts of the URL.)