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

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

    If you have to process a variable that contains the complete path (ex.: thePath = "http://stackoverflow.com/directory/subdirectory/filename.jpg") and you want to return just "filename" you can use:

    theName = thePath.split("/").slice(-1).join().split(".").shift();
    

    the result will be theName == "filename";

    To try it write the following command into the console window of your chrome debugger: window.location.pathname.split("/").slice(-1).join().split(".").shift()

    If you have to process just the file name and its extension (ex.: theNameWithExt = "filename.jpg"):

    theName = theNameWithExt.split(".").shift();
    

    the result will be theName == "filename", the same as above;

    Notes:

    1. The first one is a little bit slower cause performes more operations; but works in both cases, in other words it can extract the file name without extension from a given string that contains a path or a file name with ex. While the second works only if the given variable contains a filename with ext like filename.ext but is a little bit quicker.
    2. Both solutions work for both local and server files;

    But I can't say nothing about neither performances comparison with other answers nor for browser or OS compatibility.

    working snippet 1: the complete path

    var thePath = "http://stackoverflow.com/directory/subdirectory/filename.jpg";
    theName = thePath.split("/").slice(-1).join().split(".").shift();
    alert(theName);
      

    working snippet 2: the file name with extension

    var theNameWithExt = "filename.jpg";
    theName = theNameWithExt.split("/").slice(-1).join().split(".").shift();
    alert(theName);
      

    working snippet 2: the file name with double extension

    var theNameWithExt = "filename.tar.gz";
    theName = theNameWithExt.split("/").slice(-1).join().split(".").shift();
    alert(theName);
      

提交回复
热议问题