Explain Codes LogoExplain Codes Logo

How to get the file name from a full path using JavaScript?

javascript
regex
path
nodejs
Alex KataevbyAlex Kataev·Oct 6, 2024
TLDR

To quickly extract the file name from a path, you can utilize the split() and pop() methods elegantly:

let fileName = 'C:/path/to/file.txt'.split('/').pop(); console.log(fileName); // Outputs: file.txt

For paths in the Windows-style, you can normalize the path by using a replace() method:

let fileName = 'C:\\path\\to\\file.txt'.replace(/\\/g, '/').split('/').pop(); console.log(fileName); // Outputs: Windows has left the chat

For you Node.js enthusiasts, use the path.basename() method:

const path = require('path'); let fileName = path.basename('/path/to/file.txt'); console.log(fileName); // 'file.txt; or 'Node took over the job'

Dealing with different path delimiters

An important thing to note is that different operating systems use different path delimiters. For instance, Windows uses backslashes (\), and POSIX-compliant systems (Linux/Mac) use slashes (/). Always code cross-platform compatible solutions.

Extracting file names with a sprinkle of regex

Stepping away from splitting paths, we can use match() with the right dosage of regular expressions. It's like The One Ring, but only for file paths:

let fullPath = 'C:\\path\\to\\file.txt'; let regex = /[^\\\/]*$/; let fileName = fullPath.match(regex)[0]; console.log(fileName); // 'file.txt'; or 'Regex, you shall not pass!'

How about a little Node.js fun?

Back to Node.js, a joyous place. You can take advantage of the path.parse function for all the parsing goodness:

const path = require('path'); let parsed = path.parse('/home/user/documents/report.pdf'); let fileName = parsed.base; console.log(fileName); // 'report.pdf'; or 'Node on the case'

Let's test some unusual scenarios

A truly robust solution is one that doesn't run away from weird file paths. What if you come across some outlandish cases, like:

  • Relative paths (./file.txt)
  • Paths with too many delimiters (/path/to/file.txt)
  • Files with no extensions (/path/file)
  • Hidden files (/path/.hiddenfile) or weird file names (/path/file.tar.gz)

Can your code handle all these? Time to find out!

The matrix of regex

Take a deep breath, we're diving into that regular expression /[^\\\/]*$/:

  • [^\\\/]* - Match any character that is not a \ or / zero or more times.
  • $ - Ensure we tag along till the end of the string, getting the last file name.

Morpheus would be proud.

Flying without the regex wings

If regex is not your potion, you can embark on the journey using fundamental string methods like split and pop:

let fullPath = '/path/to/directory/file.txt'; let components = fullPath.split('/'); let fileName = components.pop(); console.log(fileName); // 'file.txt'; or 'I popped to the finish line'

The non-RegExp solution might feel old-school, but it definitely packs a punch.

Extra notes on platform considerations

Remember, a good code is like a universal translator. normalize your file paths for cross-platform compatibility.