JS: Most optimized way to remove a filename from a path in a string? JS: Most optimized way to remove a filename from a path in a string? javascript javascript

JS: Most optimized way to remove a filename from a path in a string?


Use lastIndexOf() to find the position of the last slash and get the part before the slash with substring().

str.substring(0, str.lastIndexOf("/"));


If you're using Node.js:

const path = require("path")const removeFilePart = dirname => path.parse(dirname).dirremoveFilePart("/a/b/c/d.txt")// Returns "/a/b/c"


How about this:

"path/to/a/filename.txt".split("/").slice(0, -1).join("/")+"/"