Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get absolute path in javascript

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!

like image 871
SeanStick Avatar asked Dec 06 '11 14:12

SeanStick


People also ask

What is an absolute path JavaScript?

An absolute import path is a path that starts from a root, and you need to define a root first. In a typical JavaScript/TypeScript project, a common root is the src directory.

How do I find absolute path?

You can determine the absolute path of any file in Windows by right-clicking a file and then clicking Properties. In the file properties first look at the "Location:" which is the path to the file.

What is absolute and relative path in JavaScript?

The path with reference to root directory is called absolute. The path with reference to current directory is called relative.

How do I get the full path in node JS?

We can get the path of the present script in node. js by using __dirname and __filename module scope variables. __dirname: It returns the directory name of the current module in which the current script is located.


3 Answers

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

like image 53
Anders Marzi Tornblad Avatar answered Oct 18 '22 18:10

Anders Marzi Tornblad


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];
like image 29
Gabriele Petrioli Avatar answered Oct 18 '22 19:10

Gabriele Petrioli


var full = location.pathname;
var path = full.substr(full.lastIndexOf("/") + 1);
like image 4
Saul Avatar answered Oct 18 '22 19:10

Saul