Get Filename and File Extension from Full FilePath
From a Filepath, get the Name of the File and the Files Extension ie /documents/my-photos/my-cat-yacking.png => [0]my-cat-yacking [1]jpg
Home
Short:
/* --------------------------------------------------------- break apart the path to a file return the name of the file and the extension ie /files/photos/eat-breakfast.jpg [0] eat-breakfast [1] jpg usage: [name, extension] = arrFilePathExtension(filename) -------------------------------------------------------- */ function arrFilePathExtension(filepath) { // split at each / const pathArray = filepath.split("/"); // the last item in index will be the filename with the extension const lastIndex = (pathArray.length - 1); const filename = pathArray[lastIndex]; // the (last) period . separates the files name from its extension const last_dot = filename.lastIndexOf("."); // the right part is the extension const extension = filename.slice(last_dot + 1); // left part is filename const name = filename.slice(0, last_dot); // return as array filename and file extension return [name, extension]; }
source code home