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

例子:

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

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


当前回答

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

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

其他回答

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

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

一个问题问“获取没有扩展名的文件名”参考这里,但没有解决方案。 这是由博比的溶液改进而来的溶液。

var name_without_ext = (file_name.split('\\').pop().split('/').pop().split('.'))[0];
<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>

一个简单的函数,如PHP pathInfo:

函数pathInfo(s) { s = s.match (/(.*?[\\/:])?(([^\\/:]*?)(\.[^\\/.]+?)?)(?:[?#].*)?$/); {返回文件路径:s[1]:[2],名字:[3],ext: s [4]}; } console.log(pathInfo('c:\\文件夹\\文件.txt')); console.log(pathInfo('/folder/another/file.min.js?query=1')); 输入并尝试一下: <输入oninput = " . getelementbyid(“测试”).textContent = pathInfo (this.value)。文件" value="c:\folder\folder.name\ File .ext" style="width:300px">

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

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

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