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

Answers


Try this:

   var nameString = "/app/base/controllers/filename.js";
   var filename = nameString.split("/").pop();

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

a pure regex solution: \/([^\\\/:*?\"<>|]+)$ you will get file name from group 1


Here one more detailed solution using Regular Expressions.

Alternative 1 (generic): Get a file name (whatever) from a string path.

const FILE_NAME_REGEX = /(.+)\/(.+)$/

"/home/username/my-package/my-file1.ts".replace(FILE_NAME_REGEX, '$2')
// > "my-file1.ts"
"/home/username/my-package/my-file2.js".replace(FILE_NAME_REGEX, '$2')
// > "my-file2.js"

Alternative 2 (advanced): Get only a .ts file name from a string path.

const JS_PATH = "/home/username/my-package/my-file.spec.js"
const TS_PATH = "/home/username/my-package/my-file.spec.ts"

// RegExp accepts only `.ts` file names in lower case with optional dashes and dots
const TS_REGEX = /(.+)\/([a-z.-]+\.(ts))$/

// a. Get only the file name of a `.ts` path
TS_PATH.replace(TS_REGEX, '$2')
// > "my-file.spec.ts"

// b. Otherwise it will return the complete path
JS_PATH.replace(TS_REGEX, '$2')
// > "/home/username/my-package/my-file.spec.js"

Note: Additionally you can test first the regular expressions above in order to validate them before to getting the expected value.

TS_REGEX.test(TS_PATH)
// > true

TS_REGEX.test(JS_PATH)
// > false

More information at MDN - Regular Expressions


Need Your Help

Google In-App billing, IllegalArgumentException: Service Intent must be explicit, after upgrading to Android L Dev Preview

android android-intent in-app-billing illegalargumentexception android-5.0-lollipop

My in-app billing code was working fine until I upgraded to the Android L Dev Preview. Now I get this error when my app starts. Does anyone know what's changed about L that causes this or how I sho...

SSHFS for OSX 10.8 (Mountain Lion)

ssh sftp osx-mountain-lion

In the past I used SSHFS to mount drives, so I could easily work on remote machines with software from my machine. However, when I was at the MacFUSE project page, I noticed that SSHFS has been long