Skip to main content

JavaScript function that mimics the behavior of the *NIX basename command. It deletes any prefix up to the last slash ('/') character and returns the result.

/**
 * Deletes any prefix up to the last slash ('/') character
 * and return the result (http://stackoverflow.com/a/3820412).
 *
 * @param {String} path The file path or URI address.
 * @return {String} The basename for the specified path.
 */
function baseName(path) {
    var base = new String(path).substring(path.lastIndexOf('/') + 1);
    if (base.lastIndexOf(".") != -1) {
        base = base.substring(0, base.lastIndexOf("."));
    }
    return base;
}

//
// Example Usage

baseName('/path/to/file');
>>> "file"

baseName('https://example.com/test');
>>> "test"

baseName('https://example.com/test.html');
>>> "test"