是否有一种方法,我可以得到的最后一个值(基于'\'符号)从一个完整的路径?

例子:

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

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


当前回答

我使用:

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

它取代了最后一个\,所以它也适用于文件夹。

其他回答

我使用:

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

它取代了最后一个\,所以它也适用于文件夹。

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

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

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

另一个

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

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

或者使用数组进行拆分

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

如果需要,这将是动态地将更多分隔符推入数组的方法。 如果fullPath是由代码中的字符串显式设置的,则需要转义反斜杠! 比如“C:\\Documents and Settings\\img\\ recycling log.jpg”

<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>
var filename = fullPath.replace(/^.*[\\\/]/, '')

这将处理两个\ OR / in路径