Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
The ultimate split path, with a single regex
* The ultimate split path.
* Extracts dirname, filename, extension, and trailing URL params.
* Correct handles:
* empty dirname,
* empty extension,
* random input (extracts as filename),
* multiple extensions (only extracts the last one),
* dotfiles (however, will extract extension if there is one)
* @param {string} path
* @return {Object} Object containing fields "dirname", "filename", "extension", and "params"
var splitPath = function(path) {
var result = path.replace(/\\/g, "/").match(/(.*\/)?(\..*?|.*?)(\.[^.]*?)?(#.*$|\?.*$|$)/);
return {
dirname: result[1] || "",
filename: result[2] || "",
extension: result[3] || "",
params: result[4] || ""
Copy link

guillaumegarcia13 commented Jul 22, 2018

Very useful!
Find this particular path that is not returning as expected:


Copy link

arlindosilvaneto commented Feb 11, 2020

You can use this regex for file path with full URL:


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment