How would I go about trimming/stripping the URL down to the page name...
So: http://www.BurtReynoldsMustache.com/whatever/whoever/apage.html
Would become: apage.html
Any ideas?
you do not need jquery:
var url = window.location.href;
var page = url.substring(url.lastIndexOf('/') + 1);
Edit: a good point of the possible query string:
// it might be from browser & / anywhere else
var url = window.location.href;
url = url.split('#').pop().split('?').pop();
var page = url.substring(url.lastIndexOf('/') + 1);
ok, if the location object is available, use pathname gives better result as show below, however, a url can be a string or something directly from text field or span/label. So above solution should have its place.
With location
and any link (<a>
) elements on the page, you get a load of properties that give you specific parts of the URL: protocol
, host
, port
, pathname
, search
and hash
.
You should always use these properties to extract parts of the URL in preference to hacking about with href
and probably getting it wrong for corner cases. For example, every solution posted here so far will fail if a ?query
or #fragment
is present. The answers from Rob and digitalFresh attempt to cope with them, but will still fail if a /
character is present in the query string or fragment (which is valid).
Instead, simply:
var pagename= location.pathname.split('/').pop();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With