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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 05:51:59  来源:igfitidea点击:

Get absolute path in javascript

javascripthtml

提问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.pathnamegives 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.locationobject 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:     

Documentation at MDN

MDN 上的文档

So location.pathnameis 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);