JavaScript functions for basename and dirname

A drawing of a cartoon man pointing upwards

Heads up! This post was written in 2007, so it may contain information that is no longer accurate. I keep posts like this around for historical purposes and to prevent link rot, so please keep this in mind as you're reading.

— Cory

Here are two JavaScript functions that mimic their PHP cousins.

basename() #

function basename(path) {
  return path.replace(/.*\//, '');
}

dirname() #

function dirname(path) {
  return path.match(/.*\//);
}

Unlike their PHP cousins, these functions do not support paths separated with backslashes.