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

前端 未结 23 2091
醉酒成梦
醉酒成梦 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:41

    You can perhaps use the assumption that the last dot will be the extension delimiter.

    var x = 'filename.jpg';
    var f = x.substr(0, x.lastIndexOf('.'));
    

    If file has no extension, it will return empty string. To fix that use this function

    function removeExtension(filename){
        var lastDotPosition = filename.lastIndexOf(".");
        if (lastDotPosition === -1) return filename;
        else return filename.substr(0, lastDotPosition);
    }
    

提交回复
热议问题