How to trim a file extension from a String in JavaScript?

前端 未结 23 2090
醉酒成梦
醉酒成梦 2020-11-30 17:21

For example, assuming that x = filename.jpg, I want to get filename, where filename could be any file name (Let\'s assume the file nam

23条回答
  •  误落风尘
    2020-11-30 17:49

    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 + ""
    }
    

提交回复
热议问题