7

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!

1

6 Answers 6

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

Sign up to request clarification or add additional context in comments.

1 Comment

Add a [0] after the match so that you extract the actual value. Otherwise you end with an array of matches (only one in this case)
7

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];

Comments

4
var full = location.pathname;
var path = full.substr(full.lastIndexOf("/") + 1);

Comments

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.

Comments

0

Try this:

var loc = window.location.href;
var fileNamePart = loc.substr(loc.lastIndexOf('/') + 1);

Comments

0
// "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); 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.