例如,假设x = filename.jpg,我想要获取filename,其中filename可以是任何文件名(为了简化,我们假设文件名只包含[a-zA-Z0-9-_])。

我看到x.substring(0, x.indexOf('.jpg'))在DZone片段上,但x.substring(0, x.length-4)不会表现更好吗?因为,length是一个属性,不做字符检查,而indexOf()是一个函数,做字符检查。


当前回答

在0.12.x之前的Node.js版本中:

路径。:文件名,path.extname(文件名)

当然,这也适用于0.12。X和以后。

其他回答

即使在字符串中不存在分隔符时,这也是有效的。

String.prototype.beforeLastIndex = function (delimiter) {
    return this.split(delimiter).slice(0,-1).join(delimiter) || this + ""
}

"image".beforeLastIndex(".") // "image"
"image.jpeg".beforeLastIndex(".") // "image"
"image.second.jpeg".beforeLastIndex(".") // "image.second"
"image.second.third.jpeg".beforeLastIndex(".") // "image.second.third"

也可以像这样作为一行代码使用:

var filename = "this.is.a.filename.txt";
console.log(filename.split(".").slice(0,-1).join(".") || filename + "");

编辑:这是一个更有效的解决方案:

String.prototype.beforeLastIndex = function (delimiter) {
    return this.substr(0,this.lastIndexOf(delimiter)) || this + ""
}

我喜欢用正则表达式来做。它很短,很容易理解。

(const regexppattern of [] / \ . .+$/, //查找第一个圆点及其后面的所有内容。 / \[^ /。+$/ //获取最后一个圆点及其后面的所有内容。 ) { console.log(“myFont.ttf”。替换(regexPattern”、“)) console.log(“myFont.ttf.log”。替换(regexPattern”、“)) } / *输出 myFont myFont myFont myFont.ttf * /

上述解释可能不是很严谨。如果您想获得更准确的解释,可以访问regex101进行检查

美元\ . . + \[^ /。]。+美元

我喜欢这篇文章,因为它只有一行字,读起来不难:

filename.substring(0, filename.lastIndexOf('.')) || filename

如果你使用的是Node.js,一个简单的答案就是第一条注释。 我的任务是我需要从Node服务器中删除Cloudinary中的一个图像,我只需要获得图像名称。 例子:

const path = require("path")
const image=xyz.jpg;
const img= path.parse(image).name
console.log(img) // xyz

另一个一行程序:

x.split(".").slice(0, -1).join(".")