-
-
Save guillaumegarcia13/6617fcd1aeb8b6807db733642259cc26 to your computer and use it in GitHub Desktop.
The ultimate split path, with a single regex
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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" | |
* | |
* See: https://regexr.com/3sqfe | |
* | |
* /!\ path such as \var\www\www.example.com\.hidden\index.php returns .hidden\index as extension | |
*/ | |
var splitPath = function(path) { | |
var result = path.replace(/\\/g, "/").match(/(.*\/)?(\..*?|.*?)(\.[^.]*?)?(#.*$|\?.*$|$)/); | |
return { | |
dirname: result[1] || "", | |
filename: result[2] || "", | |
extension: result[3] || "", | |
params: result[4] || "" | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment