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
Add a comment  | 

6 Answers 6

Reset to default 9

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

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