pathExtension function

String pathExtension(
  1. String path
)

File extension / without extension / change extension. Roadmap #164–165. Audited: 2026-06-12 11:26 EDT

Implementation

String pathExtension(String path) {
  // The extension dot must be in the FINAL path segment. Searching the whole
  // path made a dot in a directory name look like an extension (so the input
  // "/a.b/file" wrongly yielded "b/file"). Confine the dot to the basename
  // (after the last separator) and reject a leading-dot dotfile.
  final int slash = path.lastIndexOf('/');
  final int backslash = path.lastIndexOf(r'\');
  final int sep = slash > backslash ? slash : backslash;
  final int dotIndex = path.lastIndexOf('.');
  if (dotIndex <= sep + 1 || dotIndex == path.length - 1) return '';
  return path.substring(dotIndex + 1);
}