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

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

    This is the code I use to remove the extension from a filename, without using either regex or indexOf (indexOf is not supported in IE8). It assumes that the extension is any text after the last '.' character.

    It works for:

    • files without an extension: "myletter"
    • files with '.' in the name: "my.letter.txt"
    • unknown length of file extension: "my.letter.html"

    Here's the code:

    var filename = "my.letter.txt" // some filename
    
    var substrings = filename.split('.'); // split the string at '.'
    if (substrings.length == 1)
    {
      return filename; // there was no file extension, file was something like 'myfile'
    }
    else
    {
      var ext = substrings.pop(); // remove the last element
      var name = substrings.join(""); // rejoin the remaining elements without separator
      name = ([name, ext]).join("."); // readd the extension
      return name;
    }
    

提交回复
热议问题