Javascript JS:从字符串中的路径中删除文件名的最优化方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2187256/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 23:09:11  来源:igfitidea点击:

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

javascriptoptimization

提问by DaVince

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

我的字符串格式如下:
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/

现在我想做一些字符串操作,这使我能够非常有效地从此代码中删除“filename.txt”部分。换句话说,我希望我的字符串变成这样:
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;
}

回答by Kees de Kooter

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

使用 lastIndexOf() 查找最后一个斜杠的位置,并使用 substring() 获取斜杠之前的部分。

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

回答by Gumbo

How about this:

这个怎么样:

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

回答by Richie Bendall

If you're using Node.js:

如果您使用的是 Node.js:

const path = require("path")
const removeFilePart = dirname => path.parse(dirname).dir

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

回答by shiva2492

str = str.split('/')
str.pop()
str.join('/') + '/'

回答by Pointy

function splitPath(path) {
  var dirPart, filePart;
  path.replace(/^(.*\/)?([^/]*)$/, function(_, dir, file) {
    dirPart = dir; filePart = file;
  });
  return { dirPart: dirPart, filePart: filePart };
}

there that's better

那里更好

回答by Grodriguez

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

如果要处理来自文件上传表单的文件名,HTML5 规范建议使用以下代码:

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-statehttp://www.w3.org/TR/html5/forms.html#file-upload-state-(type=file)

参考:http: //www.w3.org/TR/html5/number-state.html#file-upload-statehttp://www.w3.org/TR/html5/forms.html#file-upload-state -(类型=文件)

回答by André Fiedler

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

回答by Юрий Светлов

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

test/dir/lib/file- _09.ege.jpg-将会-test/dir/lib/

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

file- _09.ege.jpg-将会-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;
            }            
        }