如何使用JavaScript从完整路径获取文件名?

时间:2021-09-18 16:01:00

Is there a way that I can get the last value (based on the '\' symbol) from a full path?

是否有一种方法可以从完整路径中获取最后的值(基于'\'符号)?

Example:

例子:

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

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

With this case, I just want to get recycled log.jpg from the full path in JavaScript.

在这种情况下,我只想从JavaScript的完整路径中回收log.jpg。

17 个解决方案

#1


533  

var filename = fullPath.replace(/^.*[\\\/]/, '')

This will handle both \ OR / in paths

这将同时处理\或/ in路径

#2


61  

Just for the sake of performance, I tested all the answers given here:

为了表现,我测试了这里给出的所有答案:

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

And the winner is the Split and Pop style answer, Thanks to bobince !

多亏了bobince !

#3


54  

What platform does the path come from? Windows paths are different from POSIX paths are different from Mac OS 9 paths are different from RISC OS paths are different...

这条路来自哪个平台?Windows路径不同于POSIX路径不同于Mac OS 9路径与RISC OS路径不同……

If it's a web app where the filename can come from different platforms there is no one solution. However a reasonable stab is to use both '\' (Windows) and '/' (Linux/Unix/Mac and also an alternative on Windows) as path separators. Here's a non-RegExp version for extra fun:

如果它是一个web应用程序,文件名可以来自不同的平台,那么就没有一个解决方案。然而,一个合理的方法是同时使用'\' (Windows)和'/' (Linux/Unix/Mac,以及Windows上的另一种选择)作为路径分隔符。这里有一个非regexp版本的额外乐趣:

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

#4


33  

In Node.js, you can use Path's parse module...

在节点。js,你可以使用Path的解析模块……

var path = require('path');
var file = '/home/user/dir/file.txt';

var filename = path.parse(file).base;
//=> 'file.txt'

#5


25  

Ates, your solution doesn't protect against an empty string as input. In that case, it fails with TypeError: /([^(\\|\/|\:)]+)$/.exec(fullPath) has no properties.

Ates,你的解决方案不能保护一个作为输入的空字符串。在这种情况下,它与TypeError失败:/((^(\ \ | \ \ | \:)]+)/美元.exec(fullPath)没有属性。

bobince, here's a version of nickf's that handles DOS, POSIX, and HFS path delimiters (and empty strings):

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

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

#6


17  

The following line of JavaScript code will give you the file name.

下面一行JavaScript代码将给出文件名。

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

#7


9  

Not more concise than nickf's answer, but this one directly "extracts" the answer instead of replacing unwanted parts with an empty string:

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

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

#8


6  

A question asking "get file name without extension" refer to here but no solution for that. Here is the solution modified from Bobbie's solution.

问“没有扩展名的获取文件名”的问题请参考这里,但没有解决方案。这是根据博比溶液修改的溶液。

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

#9


2  

<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>

#10


1  

The complete answer is:

完整的回答是:

<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>

#11


0  

<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>

#12


0  

Successfully Script for your question ,Full Test

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

<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)
}

#13


0  

I use:

我使用:

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

It replaces the last \ so it also works with folders.

它替换了最后一个\,因此它也可以使用文件夹。

#14


-2  

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

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

#15


-3  

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(".") );
}

#16


-5  

var fileName = filePath.split('/').pop();

var文件名= filePath.split(“/”).pop();

It works for me.

它适合我。

#17


-8  

<script type="text\javascript">   
   var path = '<%=Request.Url.GetLeftPart(UriPartial.Authority) + Request.ApplicationPath %>';
</script>

refer from http://www.codeprojectdownload.com

从http://www.codeprojectdownload.com参考

#1


533  

var filename = fullPath.replace(/^.*[\\\/]/, '')

This will handle both \ OR / in paths

这将同时处理\或/ in路径

#2


61  

Just for the sake of performance, I tested all the answers given here:

为了表现,我测试了这里给出的所有答案:

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

And the winner is the Split and Pop style answer, Thanks to bobince !

多亏了bobince !

#3


54  

What platform does the path come from? Windows paths are different from POSIX paths are different from Mac OS 9 paths are different from RISC OS paths are different...

这条路来自哪个平台?Windows路径不同于POSIX路径不同于Mac OS 9路径与RISC OS路径不同……

If it's a web app where the filename can come from different platforms there is no one solution. However a reasonable stab is to use both '\' (Windows) and '/' (Linux/Unix/Mac and also an alternative on Windows) as path separators. Here's a non-RegExp version for extra fun:

如果它是一个web应用程序,文件名可以来自不同的平台,那么就没有一个解决方案。然而,一个合理的方法是同时使用'\' (Windows)和'/' (Linux/Unix/Mac,以及Windows上的另一种选择)作为路径分隔符。这里有一个非regexp版本的额外乐趣:

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

#4


33  

In Node.js, you can use Path's parse module...

在节点。js,你可以使用Path的解析模块……

var path = require('path');
var file = '/home/user/dir/file.txt';

var filename = path.parse(file).base;
//=> 'file.txt'

#5


25  

Ates, your solution doesn't protect against an empty string as input. In that case, it fails with TypeError: /([^(\\|\/|\:)]+)$/.exec(fullPath) has no properties.

Ates,你的解决方案不能保护一个作为输入的空字符串。在这种情况下,它与TypeError失败:/((^(\ \ | \ \ | \:)]+)/美元.exec(fullPath)没有属性。

bobince, here's a version of nickf's that handles DOS, POSIX, and HFS path delimiters (and empty strings):

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

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

#6


17  

The following line of JavaScript code will give you the file name.

下面一行JavaScript代码将给出文件名。

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

#7


9  

Not more concise than nickf's answer, but this one directly "extracts" the answer instead of replacing unwanted parts with an empty string:

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

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

#8


6  

A question asking "get file name without extension" refer to here but no solution for that. Here is the solution modified from Bobbie's solution.

问“没有扩展名的获取文件名”的问题请参考这里,但没有解决方案。这是根据博比溶液修改的溶液。

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

#9


2  

<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>

#10


1  

The complete answer is:

完整的回答是:

<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>

#11


0  

<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>

#12


0  

Successfully Script for your question ,Full Test

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

<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)
}

#13


0  

I use:

我使用:

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

It replaces the last \ so it also works with folders.

它替换了最后一个\,因此它也可以使用文件夹。

#14


-2  

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

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

#15


-3  

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(".") );
}

#16


-5  

var fileName = filePath.split('/').pop();

var文件名= filePath.split(“/”).pop();

It works for me.

它适合我。

#17


-8  

<script type="text\javascript">   
   var path = '<%=Request.Url.GetLeftPart(UriPartial.Authority) + Request.ApplicationPath %>';
</script>

refer from http://www.codeprojectdownload.com

从http://www.codeprojectdownload.com参考