简体   繁体   English

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

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

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

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

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

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"

这个怎么样:

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

In node, you can use path.dirname在节点中,您可以使用path.dirname

const path = require('path')

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

directoryPath = path.dirname(fullFilePath) 

console.log(directoryPath)       // ===> '/some/given/path'

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-state http://www.w3.org/TR/html5/forms.html#file-upload-state-(type=file)参考: http : //www.w3.org/TR/html5/number-state.html#file-upload-state http://www.w3.org/TR/html5/forms.html#file-upload-state -(类型=文件)

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

there that's better那里更好

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

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM