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

前端 未结 23 1902
醉酒成梦
醉酒成梦 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:31
    var fileName = "something.extension";
    fileName.slice(0, -path.extname(fileName).length) // === "something"
    
    0 讨论(0)
  • 2020-11-30 17:33

    In node.js, the name of the file without the extension can be obtained as follows.

    const path = require('path');
    const filename = 'hello.html';
    
    path.parse(filename).name; // hello
    path.parse(filename).ext;  // .html
    

    Further explanation at Node.js documentation page.

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

    Another one-liner:

    x.split(".").slice(0, -1).join(".")
    
    0 讨论(0)
  • x.slice(0, -(x.split('.').pop().length + 1));
    
    0 讨论(0)
  • 2020-11-30 17:35

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

    x.replace(/\.[^/.]+$/, "")
    
    0 讨论(0)
  • 2020-11-30 17:35

    x.length-4 only accounts for extensions of 3 characters. What if you have filename.jpegor filename.pl?

    EDIT:

    To answer... sure, if you always have an extension of .jpg, x.length-4 would work just fine.

    However, if you don't know the length of your extension, any of a number of solutions are better/more robust.

    x = x.replace(/\..+$/, '');

    OR

    x = x.substring(0, x.lastIndexOf('.'));

    OR

    x = x.replace(/(.*)\.(.*?)$/, "$1");

    OR (with the assumption filename only has one dot)

    parts = x.match(/[^\.]+/);
    x = parts[0];
    

    OR (also with only one dot)

    parts = x.split(".");
    x = parts[0];
    
    0 讨论(0)
提交回复
热议问题