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

Viewed 53401

I have strings formatted as follows:
path/to/a/filename.txt

Now I'd like to do some string manipulation which allows me to very efficiently remove the "filename.txt" part from this code. In other words, I want my string to become this:
path/to/a/

What's the most efficient way to do this? Currently I'm splitting the string and reconnecting the seperate elements except for the last one, but I get the feeling this is a really, REALLY inefficient way to do it. Here's my current, inefficient code:

res.getPath = function(file)
{
  var elem = file.split("/");
  var str = "";
  for (var i = 0; i < elem.length-1; i++)
    str += elem[i] + "/";
  return str;
}
9 Answers

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).dir

removeFilePart("/a/b/c/d.txt")
// Returns "/a/b/c"

How about this:

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

In node, you can use path.dirname

const path = require('path')

fullFilePath = '/some/given/path/to-a-file.txt' 

directoryPath = path.dirname(fullFilePath) 

console.log(directoryPath)       // ===> '/some/given/path'
str = str.split('/')
str.pop()
str.join('/') + '/'
function splitPath(path) {
  var dirPart, filePart;
  path.replace(/^(.*\/)?([^/]*)$/, function(_, dir, file) {
    dirPart = dir; filePart = file;
  });
  return { dirPart: dirPart, filePart: filePart };
}

there that's better

test/dir/lib/file- _09.ege.jpg - Will be to - test/dir/lib/

file- _09.ege.jpg - Will be to - file- _09.ege.jpg

    console.log("test - "+getPath('test/dir/lib/file- _09.ege.jpg'));

    function getPath(path){
        path = path.match(/(^.*[\\\/]|^[^\\\/].*)/i);
        if(path != null){
            return path[0];
        }else{
            return false;
        }            
    }

console.log("test - "+getPath('test/dir/lib/file- _09.ege.jpg'));

        function getPath(path){
            path = path.match(/(^.*[\\\/]|^[^\\\/].*)/i);
            if(path != null){
                return path[0];
            }else{
                return false;
            }            
        }

Related