Skip to content

Instantly share code, notes, and snippets.

@nopjia
Last active November 7, 2022 16:22
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save nopjia/e94b5f822744b60cd106 to your computer and use it in GitHub Desktop.
Save nopjia/e94b5f822744b60cd106 to your computer and use it in GitHub Desktop.
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] || ""
};
};
@guillaumegarcia13
Copy link

Very useful!
Find this particular path that is not returning as expected:
\var\www\www.example.com\.hidden\index

See: https://regexr.com/3sqfe

@arlindosilvaneto
Copy link

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

/\.(.{3})$/

@mbtools
Copy link

mbtools commented Nov 7, 2022

Finally, something that worked for me! Thank you

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