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

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

    Node.js remove extension from full path keeping directory

    https://stackoverflow.com/a/31615711/895245 for example did path/hello.html -> hello, but if you want path/hello.html -> path/hello, you can use this:

    #!/usr/bin/env node
    const path = require('path');
    const filename = 'path/hello.html';
    const filename_parsed = path.parse(filename);
    console.log(path.join(filename_parsed.dir, filename_parsed.name));
    

    outputs directory as well:

    path/hello
    

    https://stackoverflow.com/a/36099196/895245 also achieves this, but I find this approach a bit more semantically pleasing.

    Tested in Node.js v10.15.2.

    0 讨论(0)
  • 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);
    }
    
    0 讨论(0)
  • 2020-11-30 17:44

    Simple one:

    var n = str.lastIndexOf(".");
    return n > -1 ? str.substr(0, n) : str;
    
    0 讨论(0)
  • 2020-11-30 17:46

    In Node.js versions prior to 0.12.x:

    path.basename(filename, path.extname(filename))

    Of course this also works in 0.12.x and later.

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

    The accepted answer strips the last extension part only (.jpeg), which might be a good choice in most cases.

    I once had to strip all extensions (.tar.gz) and the file names were restricted to not contain dots (so 2015-01-01.backup.tar would not be a problem):

    var name = "2015-01-01_backup.tar.gz";
    name.replace(/(\.[^/.]+)+$/, "");
    
    0 讨论(0)
  • 2020-11-30 17:46

    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('.')), '')

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