Answers:
var filename = fullPath.replace(/^.*[\\\/]/, '')
这将处理路径中的\ OR /
"/var/drop/foo/boo/moo.js".replace(/^.*[\\\/]/, '')
返回moo.js
为了性能起见,我测试了此处给出的所有答案:
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
而得奖者是Split and Pop风格的答案,这要感谢bobince!
path.split(/.*[\/|\\]/)[1];
在Node.js中,您可以使用Path的parse模块 ...
var path = require('path');
var file = '/home/user/dir/file.txt';
var filename = path.parse(file).base;
//=> 'file.txt'
basename
功能:path.basename(file)
路径来自什么平台?Windows路径不同于POSIX路径不同于Mac OS 9路径不同于RISC OS路径...
如果这是一个Web应用程序,文件名可以来自不同的平台,则没有一种解决方案。但是,合理的选择是同时使用'\'(Windows)和'/'(Linux / Unix / Mac,以及Windows上的替代名称)作为路径分隔符。这是非RegExp版本,可带来更多乐趣:
var leafname= pathname.split('\\').pop().split('/').pop();
var path = '\\Dir2\\Sub1\\SubSub1'; //path = '/Dir2/Sub1/SubSub1'; path = path.split('\\').length > 1 ? path.split('\\').slice(0, -1).join('\\') : path; path = path.split('/').length > 1 ? path.split('/').slice(0, -1).join('/') : path; console.log(path);
Ates,您的解决方案无法防止输入空字符串。在这种情况下,它将失败TypeError: /([^(\\|\/|\:)]+)$/.exec(fullPath) has no properties
。
bobince,这是nickf的一个版本,可以处理DOS,POSIX和HFS路径定界符(以及空字符串):
return fullPath.replace(/^.*(\\|\/|\:)/, '');
比nickf的答案更简洁,但这是直接“提取”答案的方法,而不是用空字符串替换不需要的部分:
var filename = /([^\\]+)$/.exec(fullPath)[1];
<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>
完整的答案是:
<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>
在您的项目中几乎没有什么功能可以从Windows的完整路径以及GNU / Linux和UNIX绝对路径确定文件名。
/**
* @param {String} path Absolute path
* @return {String} File name
* @todo argument type checking during runtime
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/lastIndexOf
* @example basename('/home/johndoe/github/my-package/webpack.config.js') // "webpack.config.js"
* @example basename('C:\\Users\\johndoe\\github\\my-package\\webpack.config.js') // "webpack.config.js"
*/
function basename(path) {
let separator = '/'
const windowsSeparator = '\\'
if (path.includes(windowsSeparator)) {
separator = windowsSeparator
}
return path.slice(path.lastIndexOf(separator) + 1)
}
<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>
成功为您的问题编写脚本,全面测试
<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)
}
对于“文件名”和“路径”,此解决方案都更加简单和通用。
const str = 'C:\\Documents and Settings\\img\\recycled log.jpg';
// regex to split path to two groups '(.*[\\\/])' for path and '(.*)' for file name
const regexPath = /^(.*[\\\/])(.*)$/;
// execute the match on the string str
const match = regexPath.exec(str);
if (match !== null) {
// we ignore the match[0] because it's the match for the hole path string
const filePath = match[1];
const fileName = match[2];
}
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(".") );
}