【问题标题】:How to get the file name from a full path using JavaScript?如何使用 JavaScript 从完整路径中获取文件名?
【发布时间】:2010-09-30 05:13:45
【问题描述】:

有没有办法从完整路径中获取最后一个值(基于“\”符号)?

例子:

C:\Documents and Settings\img\recycled log.jpg

在这种情况下,我只想从 JavaScript 的完整路径中获取recycled log.jpg

【问题讨论】:

    标签: javascript


    【解决方案1】:
    var filename = fullPath.replace(/^.*[\\\/]/, '')
    

    这将同时处理路径中的 \ 或 /

    【讨论】:

    • 在 MAC OSX 上不起作用,使用 chrome,它在 \ 之后转义字符
    • 根据本站,使用replacesubstr很多,可以和lastIndexOf('/')+1配合使用:jsperf.com/replace-vs-substring
    • @nickf Nick,不确定我哪里出错了,但是当文件路径有单斜杠时,代码对我不起作用。 Fiddle,虽然对于`\\`,它工作正常。
    • 我刚刚在我的控制台上运行了这个,它非常适合正斜杠:"/var/drop/foo/boo/moo.js".replace(/^.*[\\\/]/, '') 返回moo.js
    • @ZloySmiertniy 有几个很好的在线正则表达式解释器。 rick.measham.id.au/paste/explain.pl?regex=%2F%5E.*%5B%5C%5C%5C%2F%5D%2F 和regexper.com/#%2F%5E.*%5B%5C%5C%5C%2F%5D%2F 应该会有所帮助。 (此处的链接已损坏,但复制粘贴到选项卡中即可)
    【解决方案2】:

    只是为了性能,我测试了这里给出的所有答案:

    var substringTest = function (str) {
        return str.substring(str.lastIndexOf('/')+1);
    }
    
    var replaceTest = function (str) {
        return str.replace(/^.*(\\|\/|\:)/, '');
    }
    
    var execTest = function (str) {
        return /([^\\]+)$/.exec(str)[1];
    }
    
    var splitTest = function (str) {
        return str.split('\\').pop().split('/').pop();
    }
    
    substringTest took   0.09508600000000023ms
    replaceTest   took   0.049203000000000004ms
    execTest      took   0.04859899999999939ms
    splitTest     took   0.02505500000000005ms
    

    而获胜者是 Split and Pop 风格的答案,感谢 bobince

    【讨论】:

    • 根据元讨论,请在其他答案中添加适当的引用。更好地解释您如何分析运行时也会有所帮助。
    • 也可以随意对这个版本进行基准测试。应该支持 Mac 和 Windows 文件路径。 path.split(/.*[\/|\\]/)[1];
    • 测试不正确。 substringTest 仅搜索正斜杠, execTest - 仅搜索反斜杠,而其余两个处理两个斜杠。实际结果不相关(不再)。看看这个:jsperf.com/name-from-path
    • @Grief 该链接不再有效。
    【解决方案3】:

    在 Node.js 中,你可以使用Path's parse module...

    var path = require('path');
    var file = '/home/user/dir/file.txt';
    
    var filename = path.parse(file).base;
    //=> 'file.txt'
    

    【讨论】:

    • 如果使用 Node.js,您可以使用 basename 函数:path.basename(file)
    【解决方案4】:

    路径来自什么平台? Windows 路径不同于 POSIX 路径不同于 Mac OS 9 路径不同于 RISC OS 路径不同...

    如果它是一个文件名可以来自不同平台的网络应用程序,那么没有一个解决方案。然而,合理的做法是同时使用 '\' (Windows) 和 '/' (Linux/Unix/Mac 以及 Windows 上的替代方案) 作为路径分隔符。这里有一个非 RegExp 版本,更有趣:

    var leafname= pathname.split('\\').pop().split('/').pop();
    

    【讨论】:

    • 您可能想要添加经典的 MacOS ( 的形式到 POSIX 路径
    • 你可以只使用 pop() 而不是 reverse()[0]。它也修改了原始数组,但在你的情况下没关系。
    • 我想知道我们如何创建一个对应物来获得路径。
    • 类似var path = '\\Dir2\\Sub1\\SubSub1'; //path = '/Dir2/Sub1/SubSub1'; path = path.split('\\').length > 1 ? path.split('\\').slice(0, -1).join('\\') : path; path = path.split('/').length > 1 ? path.split('/').slice(0, -1).join('/') : path; console.log(path);
    • 命名“leafname”源自目录/文件结构名称“Tree”,tree的第一件事是root,最后是leaves =>文件名是treepath的最后一个东西=> leaf :-)
    【解决方案5】:

    Ates,您的解决方案不能防止空字符串作为输入。在这种情况下,它会以TypeError: /([^(\\|\/|\:)]+)$/.exec(fullPath) has no properties 失败。

    bobince,这是处理 DOS、POSIX 和 HFS 路径分隔符(和空字符串)的 nickf 版本:

    return fullPath.replace(/^.*(\\|\/|\:)/, '');
    

    【讨论】:

    • 如果我们用PHP编写这段JS代码,我们需要为每个\添加一个额外的\
    【解决方案6】:

    以下 JavaScript 代码行将为您提供文件名。

    var z = location.pathname.substring(location.pathname.lastIndexOf('/')+1);
    alert(z);
    

    【讨论】:

      【解决方案7】:

      另一个

      var filename = fullPath.split(/[\\\/]/).pop();
      

      这里split 有一个带有character class 的正则表达式
      这两个字符必须用'\'转义

      或者使用array to split

      var filename = fullPath.split(['/','\\']).pop();
      

      如果需要,这将是动态将更多分隔符推入数组的方法。
      如果 fullPath 由代码中的字符串显式设置,则需要 escape the backslash!
      "C:\\Documents and Settings\\img\\recycled log.jpg"

      【讨论】:

      • 关于“要拆分的数组”,我没有看到将数组作为分隔符列表传递的选项。事实上,文档声明“如果分隔符是一个数组,则该数组被强制转换为字符串并用作分隔符。”
      • .split(['/','\\']).split("/,\\") 一样,这绝对不是你想要的。
      【解决方案8】:

      没有比 nickf 的 answer 更简洁,但是这个直接“提取”了答案,而不是用空字符串替换不需要的部分:

      var filename = /([^\\]+)$/.exec(fullPath)[1];
      

      【讨论】:

        【解决方案9】:

        不需要专门处理反斜杠;大多数答案不处理搜索参数。

        现代方法是简单地使用URL API 并获取pathname 属性。 API 将反斜杠规范化为斜杠。

        要将生成的%20 解析为空格,只需将其传递给decodeURIComponent

        const getFileName = (fileName) => new URL(fileName).pathname.split("/").pop();
        
        // URLs need to have the scheme portion, e.g. `file://` or `https://`.
        console.log(getFileName("file://C:\\Documents and Settings\\img\\recycled log.jpg")); // "recycled%20log.jpg"
        console.log(decodeURIComponent(getFileName("file://C:\\Documents and Settings\\img\\recycled log.jpg"))); // "recycled log.jpg"
        console.log(getFileName("https://example.com:443/path/to/file.png?size=480")); // "file.png"
        .as-console-wrapper { max-height: 100% !important; top: 0; }

        如果您总是希望路径的最后一个非空部分(例如file.png 来自https://example.com/file.png/),请在.pop() 之前添加.filter(Boolean)

        如果您只有相对 URL,但仍只想获取文件名,请使用 second argument of the URL constructor 传递基本来源。 "https://example.com" 足够了:new URL(fileName, "https://example.com")。也可以将 "https://" 添加到您的 fileName — URL 构造函数接受 https://path/to/file.ext 作为有效 URL。

        【讨论】:

          【解决方案10】:

          询问“获取不带扩展名的文件名”的问题请参阅此处,但没有解决方案。 这是从 Bobbie 的解决方案修改而来的解决方案。

          var name_without_ext = (file_name.split('\\').pop().split('/').pop().split('.'))[0];
          

          【讨论】:

            【解决方案11】:

            我使用:

            var lastPart = path.replace(/\\$/,'').split('\\').pop();
            

            它替换了最后一个 \,因此它也适用于文件夹。

            【讨论】:

              【解决方案12】:
              <script type="text/javascript">
                  function test()
                  {
                      var path = "C:/es/h221.txt";
                      var pos =path.lastIndexOf( path.charAt( path.indexOf(":")+1) );
                      alert("pos=" + pos );
                      var filename = path.substring( pos+1);
                      alert( filename );
                  }
              </script>
              <form name="InputForm"
                    action="page2.asp"
                    method="post">
                  <P><input type="button" name="b1" value="test file button"
                  onClick="test()">
              </form>
              

              【讨论】:

                【解决方案13】:

                在您的项目中包含一个小函数,用于根据 Windows 的完整路径以及 GNU/Linux 和 UNIX 绝对路径确定文件名。

                /**
                 * @param {String} path Absolute path
                 * @return {String} File name
                 * @todo argument type checking during runtime
                 * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes
                 * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice
                 * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/lastIndexOf
                 * @example basename('/home/johndoe/github/my-package/webpack.config.js') // "webpack.config.js"
                 * @example basename('C:\\Users\\johndoe\\github\\my-package\\webpack.config.js') // "webpack.config.js"
                 */
                function basename(path) {
                  let separator = '/'
                
                  const windowsSeparator = '\\'
                
                  if (path.includes(windowsSeparator)) {
                    separator = windowsSeparator
                  }
                
                  return path.slice(path.lastIndexOf(separator) + 1)
                }
                

                【讨论】:

                  【解决方案14】:

                  对于“文件名”和“路径”,此解决方案更加简单和通用。

                  parsePath = (path) => {
                      // regex to split path (untile last / or \ to two groups '(.*[\\\/])' for path and '(.*)' (untile the end after the \ or / )for file name
                      const regexPath = /^(?<path>(.*[\\\/])?)(?<filename>.*)$/;
                  
                      const match = regexPath.exec(path);
                      if (path && match) {
                          return {
                              path: match.groups.path,
                              filename: match.groups.filename
                          }
                      }
                      throw Error("Error parsing path");
                  }
                  
                  // example
                  const str = 'C:\\Documents and Settings\\img\\recycled log.jpg';
                  parsePath(str);
                  

                  【讨论】:

                  • 可以通过在代码中添加一些解释来提高答案的质量。一些寻找这个答案的人可能是编码或正则表达式的新手,提供上下文的小文本将有助于理解。
                  • 希望这种方式更好:)
                  【解决方案15】:

                  完整的答案是:

                  <html>
                      <head>
                          <title>Testing File Upload Inputs</title>
                          <script type="text/javascript">
                  
                          function replaceAll(txt, replace, with_this) {
                              return txt.replace(new RegExp(replace, 'g'),with_this);
                          }
                  
                          function showSrc() {
                              document.getElementById("myframe").href = document.getElementById("myfile").value;
                              var theexa = document.getElementById("myframe").href.replace("file:///","");
                              var path = document.getElementById("myframe").href.replace("file:///","");
                              var correctPath = replaceAll(path,"%20"," ");
                              alert(correctPath);
                          }
                          </script>
                      </head>
                      <body>
                          <form method="get" action="#"  >
                              <input type="file"
                                     id="myfile"
                                     onChange="javascript:showSrc();"
                                     size="30">
                              <br>
                              <a href="#" id="myframe"></a>
                          </form>
                      </body>
                  </html>
                  

                  【讨论】:

                    【解决方案16】:
                    <html>
                        <head>
                            <title>Testing File Upload Inputs</title>
                            <script type="text/javascript">
                                <!--
                                function showSrc() {
                                    document.getElementById("myframe").href = document.getElementById("myfile").value;
                                    var theexa = document.getElementById("myframe").href.replace("file:///","");
                                    alert(document.getElementById("myframe").href.replace("file:///",""));
                                }
                                // -->
                            </script>
                        </head>
                        <body>
                            <form method="get" action="#"  >
                                <input type="file" 
                                       id="myfile" 
                                       onChange="javascript:showSrc();" 
                                       size="30">
                                <br>
                                <a href="#" id="myframe"></a>
                            </form>
                        </body>
                    </html>
                    

                    【讨论】:

                    • 虽然这段代码 sn-p 可以解决问题,但including an explanation 确实有助于提高帖子的质量。请记住,您是在为将来的读者回答问题,而这些人可能不知道您提出代码建议的原因。
                    【解决方案17】:

                    成功为您的问题编写脚本,完整测试

                    <script src="~/Scripts/jquery-1.10.2.min.js"></script>
                    
                    <p  title="text" id="FileNameShow" ></p>
                    <input type="file"
                       id="myfile"
                       onchange="javascript:showSrc();"
                       size="30">
                    


                    <script type="text/javascript">
                    
                    function replaceAll(txt, replace, with_this) {
                        return txt.replace(new RegExp(replace, 'g'), with_this);
                    }
                    
                    function showSrc() {
                        document.getElementById("myframe").href = document.getElementById("myfile").value;
                        var theexa = document.getElementById("myframe").href.replace("file:///", "");
                        var path = document.getElementById("myframe").href.replace("file:///", "");
                        var correctPath = replaceAll(path, "%20", " ");
                       alert(correctPath);
                        var filename = correctPath.replace(/^.*[\\\/]/, '')
                        $("#FileNameShow").text(filename)
                    }
                    

                    【讨论】:

                      【解决方案18】:

                      PHP pathInfo 之类的简单函数:

                      function pathInfo(s) {
                          s=s.match(/(.*?[\\/:])?(([^\\/:]*?)(\.[^\\/.]+?)?)(?:[?#].*)?$/);
                          return {path:s[1],file:s[2],name:s[3],ext:s[4]};
                      }
                      
                      console.log( pathInfo('c:\\folder\\file.txt') );
                      
                      console.log( pathInfo('/folder/another/file.min.js?query=1') );
                      Type and try it:
                      <input oninput="document.getElementById('test').textContent=pathInfo(this.value).file" value="c:\folder\folder.name\file.ext" style="width:300px">

                      【讨论】:

                        【解决方案19】:
                        function getFileName(path, isExtension){
                        
                          var fullFileName, fileNameWithoutExtension;
                        
                          // replace \ to /
                          while( path.indexOf("\\") !== -1 ){
                            path = path.replace("\\", "/");
                          }
                        
                          fullFileName = path.split("/").pop();
                          return (isExtension) ? fullFileName : fullFileName.slice( 0, fullFileName.lastIndexOf(".") );
                        }
                        

                        【讨论】:

                          【解决方案20】:

                          var file_name = file_path.substring(file_path.lastIndexOf('/'));

                          【讨论】:

                            猜你喜欢
                            • 1970-01-01
                            • 2010-11-27
                            • 1970-01-01
                            • 2010-12-10
                            • 1970-01-01
                            • 1970-01-01
                            • 2012-01-11
                            • 1970-01-01
                            相关资源
                            最近更新 更多