JavaScript Functions for basename and dirname

Two JavaScript functions that mimic their PHP cousins.

basename()

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

dirname()

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

Sample output

Input dirname() basename()
/folder/subfolder/file.ext /folder/subfolder/ file.ext
/folder/subfolder /folder/ subfolder
/file.ext file.ext /
file.ext file.ext null

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

Author avatar

About the author

Creator of Surreal CMS and other web things. Follow me for tweets about JavaScript, CSS, and web programming.