JavaScript Functions for basename and dirname

Two JavaScript functions that mimic their PHP cousins.


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


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

New Hampshirite building web apps in Florida. Creator of Surreal CMS, Postleaf, and DirtyMarkup.

Need to get in touch? Catch me on Twitter.