0

How can I get the path name from the below URL?

file:///index.html/temp/data

I understand that /temp/data is the pathname.

window.location.pathname gives me index.html/temp/data

Praveer Kumar
  • 912
  • 1
  • 12
  • 25
  • Try using `.split` https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split – Vladimir Bogomolov Jan 16 '20 at 09:03
  • I would create an `a` add it as `href` and use the properties given (pathname, hostname, host). – Lain Jan 16 '20 at 09:09
  • Does this answer your question? [How do I parse a URL into hostname and path in javascript?](https://stackoverflow.com/questions/736513/how-do-i-parse-a-url-into-hostname-and-path-in-javascript) – Peter B Jan 16 '20 at 09:09
  • 2
    What `window.location.pathname` gives you **is** the path name. `index.html` is part of the path, it isn't the hostname. (The hostname is the bit which goes between `//` and `/` and is blank for your file scheme URL). – Quentin Jan 16 '20 at 09:09

4 Answers4

1

Unfortunately if your url is file:///index.html/temp/data then the pathname will be everything after file://, so in your case it should return /index.html/temp/data.

I don't think there is a build in solution to handle this.

To solve the problem above you can try to do

window.location.pathname.split('.html/')[1]
Fisken
  • 189
  • 5
0

You can use RegExp.match to get the desired path

let [path] = 'index.html/temp/data'.match(/(\/\w*)+/);
console.log(path)

let [path2] = 'index.htm/temp/data'.match(/(\/\w*)+/);
console.log(path2)
AZ_
  • 3,094
  • 1
  • 9
  • 19
0

Try this:

console.log (new URL("file:///index.html/temp/data")).

This will log an object with various properties such as hostname and pathname which I think is what you looking for.

Hope it helps!

AllJs
  • 1,760
  • 4
  • 27
  • 48
-1

If that is the page you have loaded, you should be able to use location.pathname to give you the path.

Otherwise, if that is just a string you have string.split('/')[3] but you should probably do some validation to make sure it is always after the 4th '/'

ebdm
  • 15
  • 1
  • 9
  • No, It didnt give me the path name, it returned me `index.html/temp/data`. If my URL is http://localhost:8080/temp/data then `window.location.pathname` gave me `/temp/data` – Praveer Kumar Jan 16 '20 at 09:06
  • @PraveerKumar I just revised my answer – ebdm Jan 16 '20 at 09:07
  • 1
    @PraveerKumar — In the question you claimed that `window.location.pathname` gave you `index.html`, now you claim it gives you `index.html/temp/data`. Which is it? – Quentin Jan 16 '20 at 09:07