Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get File Name and Parent Folder of URL

This javascript will get the whole path and the file name however the idea is to retrieve the file name + extension and its parent folder so it returns this:

/thisfolder/thanks.html

var url = "www.example.com/get/thisfolder/thanks.html";
var path = url.substring(url.indexOf('/')+1, url.lastIndexOf('.'));
alert(path)

JS Fiddle

like image 289
Evan Avatar asked Mar 23 '15 13:03

Evan


People also ask

How do I get the parent directory of a file?

Use File 's getParentFile() method and String. lastIndexOf() to retrieve just the immediate parent directory. There are several variants to retain/drop the prefix and trailing separator. You can either use the same FilenameUtils class to grab the name from the result, use lastIndexOf , etc.

Does URL contain filename?

The filename is the last part of the URL from the last trailing slash. For example, if the URL is http://www.example.com/dir/file.html then file. html is the file name.

What is the name of parent folder?

A folder located within another folder is called a sub-folder. The main folder is called the parent folder. Folders and sub-folders help us to keep our files neatly.

How do I go back to a parent folder in HTML?

go back a file __dirname. use __dirname to go to parent folder. dirname(__file__) go back.


2 Answers

Using .split(), you can select the last 2 elements and join them together after:

var url = "www.example.com/get/thisfolder/thanks.html";
var path = url.split('/').slice(-2).join('/'); 
alert(path);
like image 146
Karl-André Gagnon Avatar answered Sep 28 '22 15:09

Karl-André Gagnon


You could split by /:

var parts = url.split("/");
var filename = parts.pop();
var parent = parts.pop();
like image 25
sp00m Avatar answered Sep 28 '22 16:09

sp00m