Javascript 在javascript中获取绝对路径
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8401879/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get absolute path in javascript
提问by SeanStick
Can you get the absolute path in html.
你能得到html中的绝对路径吗?
If i use location.href i can get the url but how can i trim the filename.html ?
如果我使用 location.href 我可以获得 url 但我如何修剪 filename.html ?
IS there a better way to get the path.
有没有更好的方法来获得路径。
Thanks!
谢谢!
回答by Anders Tornblad
location.pathname
gives you the local part of the url.
location.pathname
为您提供网址的本地部分。
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
上面只给你最后一部分。例如,如果你在http://somedomain/somefolder/filename.html
,它会给你filename.html
回答by Saul
var full = location.pathname;
var path = full.substr(full.lastIndexOf("/") + 1);
回答by Gabriele Petrioli
For this page if you inspect the window.location
object you will see
对于此页面,如果您检查window.location
对象,您将看到
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.
这location.pathname
就是你想要的。如果您想提取最后一部分,请使用正则表达式。
var lastpart = window.location.pathname.match(/[^\/]+$/)[0];
回答by igors
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
.
并且不要担心它会与第一个 '/' 匹配,因为 '+' 是一个贪婪的量词,这意味着它会尽可能多地匹配。第一部分 '[^?]' 是在参数之前停止匹配,因为 '/' 可以出现在像t.php?param1=val1/val2
.
回答by am0wa
// "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);
回答by Abdul Munim
Try this:
尝试这个:
var loc = window.location.href;
var fileNamePart = loc.substr(loc.lastIndexOf('/') + 1);