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

前端 未结 23 1901
醉酒成梦
醉酒成梦 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 + ""
    }
    
    0 讨论(0)
  • 2020-11-30 17:50

    Here's another regex-based solution:

    filename.replace(/\.[^.$]+$/, '');
    

    This should only chop off the last segment.

    0 讨论(0)
  • 2020-11-30 17:51

    I like this one because it is a one liner which isn't too hard to read:

    filename.substring(0, filename.lastIndexOf('.')) || filename
    
    0 讨论(0)
  • 2020-11-30 17:53

    If you know the length of the extension, you can use x.slice(0, -4) (where 4 is the three characters of the extension and the dot).

    If you don't know the length @John Hartsock regex would be the right approach.

    If you'd rather not use regular expressions, you can try this (less performant):

    filename.split('.').slice(0, -1).join('.')
    

    Note that it will fail on files without extension.

    0 讨论(0)
  • 2020-11-30 17:53

    I would use something like x.substring(0, x.lastIndexOf('.')). If you're going for performance, don't go for javascript at all :-p No, one more statement really doesn't matter for 99.99999% of all purposes.

    0 讨论(0)
提交回复
热议问题