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
|
9 Answers
Reset to default 161Use 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
版权声明:本文标题:javascript - JS: Most optimized way to remove a filename from a path in a string? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736844392a1955238.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
split
is actually very fast, but definitely not the fastest way... – D'Arcy Rittich Commented Feb 2, 2010 at 20:15