Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get filename from string path in javascript?

How to get the filename from string-path in javascript?

Here is my code

var nameString = "/app/base/controllers/filename.js"; //this is the input path string 

do something here to get only the filename

var name = ???   //this value should equal to filename.js 
like image 614
001 Avatar asked Aug 04 '12 03:08

001


People also ask

What is the file name in a URL?

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.


2 Answers

Try this:

   var nameString = "/app/base/controllers/filename.js";    var filename = nameString.split("/").pop(); 
like image 149
levi Avatar answered Oct 06 '22 01:10

levi


I don't know why you'd want to us a regex to do this. Surely the following would be sufficient:

var nameString = "/app/base/controllers/filename.js"; var nameArray = nameString.split('/'); var name = nameArray[nameArray.length - 1]; 
like image 45
Brandon Avatar answered Oct 06 '22 00:10

Brandon