是否有一种方法,我可以得到的最后一个值(基于'\'符号)从一个完整的路径?
例子:
C:\Documents and Settings\img\recycled log.jpg
在这种情况下,我只想从JavaScript的完整路径中回收log.jpg。
是否有一种方法,我可以得到的最后一个值(基于'\'符号)从一个完整的路径?
例子:
C:\Documents and Settings\img\recycled log.jpg
在这种情况下,我只想从JavaScript的完整路径中回收log.jpg。
当前回答
<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>
其他回答
不是比nickf的回答更简洁,但是这个直接“提取”了答案,而不是用空字符串替换不需要的部分:
var filename = /([^\\]+)$/.exec(fullPath)[1];
我使用:
var lastPart = path.replace(/\\$/,'').split('\\').pop();
它取代了最后一个\,所以它也适用于文件夹。
下面这行JavaScript代码将提供文件名。
var z = location.pathname.substring(location.pathname.lastIndexOf('/')+1);
alert(z);
另一个
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 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>