How to trim a file extension from a String in Java

2019-01-16 01:53发布

For example, assuming that x = filename.jpg, I want to get filename, where filename could be any file name (Let's assume the file name only contains [a-zA-Z0-9-_] to simplify.).

I saw x.substring(0, x.indexOf('.jpg')) on DZone Snippets, but wouldn't x.substring(0, x.length-4) perform better? Because, length is a property and doesn't do character checking whereas indexOf() is a function and does character checking.

24条回答
Lonely孤独者°
2楼-- · 2019-01-16 02:25

Not sure what would perform faster but this would be more reliable when it comes to extension like .jpeg or .html

x.replace(/\.[^/.]+$/, "")
查看更多
相关推荐>>
3楼-- · 2019-01-16 02:25

Another one-liner:

x.split(".").slice(0, -1).join(".")
查看更多
神经病院院长
4楼-- · 2019-01-16 02:26

This works, even when the delimiter is not present in the string.

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"

Can also be used as a one-liner like this:

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

EDIT: This is a more efficient solution:

String.prototype.beforeLastIndex = function (delimiter) {
    return this.substr(0,this.lastIndexOf(delimiter)) || this + ""
}
查看更多
叛逆
5楼-- · 2019-01-16 02:26

I don't know if it's a valid option but I use this:

name = filename.split(".");
// trimming with pop()
name.pop();
// getting the name with join()
name.join(''); // empty string since default separator is ', '

It's not just one operation I know, but at least it should always work!

查看更多
我欲成王,谁敢阻挡
6楼-- · 2019-01-16 02:26
x.slice(0, -(x.split('.').pop().length + 1));
查看更多
手持菜刀,她持情操
7楼-- · 2019-01-16 02:27

Though it's pretty late, I will add another approach to get the filename without extension using plain old JS-

path.replace(path.substr(path.lastIndexOf('.')), '')

查看更多
登录 后发表回答