Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I trim/strip the URL down to the page name?

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?

like image 687
Barrie Reader Avatar asked Jul 09 '10 13:07

Barrie Reader


2 Answers

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.

like image 89
ccppjava Avatar answered Oct 06 '22 09:10

ccppjava


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();
like image 31
bobince Avatar answered Oct 06 '22 10:10

bobince