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

例子:

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

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


当前回答

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

其他回答

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

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

下面这行JavaScript代码将提供文件名。

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

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

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

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

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

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

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

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