JS:最优化的方法是从字符串中的路径中删除文件名? [英] JS: Most optimized way to remove a filename from a path in a string?
问题描述
我的字符串格式如下:
path / to / a / filename.txt
I have strings formatted as follows:
path/to/a/filename.txt
现在我想做一些字符串操作,这使我能够非常有效地从这段代码中删除filename.txt部分。换句话说,我希望我的字符串变为:
path / to / a /
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;
}
推荐答案
使用lastIndexOf()查找最后一个斜杠的位置,并使用substring()获取斜杠之前的部分。
Use lastIndexOf() to find the position of the last slash and get the part before the slash with substring().
str.substring(0, str.lastIndexOf("/"));
这篇关于JS:最优化的方法是从字符串中的路径中删除文件名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!