admin管理员组文章数量:1252680
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!
Share Improve this question edited Dec 6, 2011 at 14:56 Curtis 103k68 gold badges277 silver badges357 bronze badges asked Dec 6, 2011 at 14:54 SeanStickSeanStick 991 gold badge2 silver badges10 bronze badges 1- Get yourself a JavaScript reference: MDN window.location – epascarello Commented Dec 6, 2011 at 14:58
6 Answers
Reset to default 9location.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
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:
Documentation at MDN
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];
var full = location.pathname;
var path = full.substr(full.lastIndexOf("/") + 1);
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
.
Try this:
var loc = window.location.href;
var fileNamePart = loc.substr(loc.lastIndexOf('/') + 1);
// "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);
本文标签: htmlGet absolute path in javascriptStack Overflow
版权声明:本文标题:html - Get absolute path in javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738305989a2073833.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论