Can you get the absolute path in html.
If i use location.href i can get the url but how can i trim the filename.html ?
IS there a better way to get the path.
Thanks!
Can you get the absolute path in html.
If i use location.href i can get the url but how can i trim the filename.html ?
IS there a better way to get the path.
Thanks!
location.pathname gives you the local part of the url.
var filename = location.pathname.match(/[^\/]+$/)[0]
The above gives you only the very last part. For example, if you are on http://somedomain/somefolder/filename.html, it will give you filename.html
[0] after the match so that you extract the actual value. Otherwise you end with an array of matches (only one in this case)For this page if you inspect the window.location object you will see
hash:
host: stackoverflow.com
hostname: stackoverflow.com
href: http://stackoverflow.com/questions/8401879/get-absolute-path-in-javascript
pathname: /questions/8401879/get-absolute-path-in-javascript
port:
protocol: http:
search:
So location.pathname is what you want. And if you want to extract the last part use regex.
var lastpart = window.location.pathname.match(/[^\/]+$/)[0];
Or if you need everything from protocol to last '/' you can use:
new RegExp('[^?]+/').exec(location.href)
and don't worry that it will match to the first '/' because '+' is a greedy quantifier, which means it will match as much as it can. First part '[^?]' is to stop matching before parameters because '/' can appear in parameter values like t.php?param1=val1/val2.