Reputation: 99
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!
Upvotes: 7
Views: 60306
Reputation: 19345
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
Upvotes: 9
Reputation: 8407
// "http://localhost:8080/public/help/index.html"
const loc = window.location.href;
// "http://localhost:8080/public/help/"
const path = loc.substr(0, loc.lastIndexOf('/') + 1);
Upvotes: 0
Reputation: 358
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
.
Upvotes: 1
Reputation: 196236
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];
Upvotes: 7
Reputation: 19217
Try this:
var loc = window.location.href;
var fileNamePart = loc.substr(loc.lastIndexOf('/') + 1);
Upvotes: 0
Reputation: 18071
var full = location.pathname;
var path = full.substr(full.lastIndexOf("/") + 1);
Upvotes: 4