admin管理员组

文章数量:1134247

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;
}

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;
}
Share Improve this question edited Feb 2, 2010 at 20:11 DaVince asked Feb 2, 2010 at 20:06 DaVinceDaVince 1,0641 gold badge8 silver badges14 bronze badges 2
  • Very similar: stackoverflow.com/questions/2161511 – Gumbo Commented Feb 2, 2010 at 20:12
  • 1 split is actually very fast, but definitely not the fastest way... – D'Arcy Rittich Commented Feb 2, 2010 at 20:15
Add a comment  | 

9 Answers 9

Reset to default 161

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 getDirname(pathname, separator) {
    var parts = pathname.split(separator);
    if (parts[parts.length - 1].indexOf('.') > -1) {
        return parts.slice(0, -1).join(separator)
    }
    return pathname;
}

Usage:

var dir = getDirname(url.parse(request.url).pathname, '/');

.

var dir = getDirname(path.join('foo', 'bar', 'text.txt'), path.sep);
function splitPath(path) {
  var dirPart, filePart;
  path.replace(/^(.*\/)?([^/]*)$/, function(_, dir, file) {
    dirPart = dir; filePart = file;
  });
  return { dirPart: dirPart, filePart: filePart };
}

there that's better

If this is to process a filename from a file upload form, the HTML5 spec recommends the following code:

function extractFilename(path) {
  if (path.substr(0, 12) == "C:\\fakepath\\")
    return path.substr(12); // modern browser
  var x;
  x = path.lastIndexOf('/');
  if (x >= 0) // Unix-based path
    return path.substr(x+1);
  x = path.lastIndexOf('\\');
  if (x >= 0) // Windows-based path
    return path.substr(x+1);
  return path; // just the filename
}

Reference: http://www.w3.org/TR/html5/number-state.html#file-upload-state http://www.w3.org/TR/html5/forms.html#file-upload-state-(type=file)

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;
            }            
        }

本文标签: javascriptJS Most optimized way to remove a filename from a path in a stringStack Overflow