extname function
Extracts the file extension (including the leading dot, e.g. .png) from path,
or returns an empty string "" if none exists.
Designed as a lightweight replacement for p.extension from package:path.
Correctly handles trailing slashes, hidden files (dotfiles like .gitignore),
and paths containing dots in directory names (e.g. /path.v1/file).
Examples
extname('photo.jpg'); // Returns: '.jpg'
extname('/path/to/doc.pdf'); // Returns: '.pdf'
extname('archive.tar.gz'); // Returns: '.gz'
extname('README'); // Returns: ''
extname('/dir.v1/file'); // Returns: ''
extname('.gitignore'); // Returns: ''
Implementation
String extname(String path) {
final lastSlash = path.lastIndexOf(RegExp(r'[/\\]'));
final lastDot = path.lastIndexOf('.');
if (lastDot > lastSlash + 1) {
return path.substring(lastDot);
}
return '';
}