如何从一个完整的路径使用JavaScript的文件名?

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

例子:

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

在这种情况下,我只想从JavaScript的完整路径中获得recycled log.jpg

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

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

路径来自哪个平台?Windows路径不同POSIX路径不同Mac OS 9路径不同RISC OS路径不同…

如果它是一个web应用程序,文件名可以来自不同的平台,那么就没有一个解决方案。然而,一个合理的尝试是同时使用'\' (Windows)和'/' (Linux/Unix/Mac和Windows上的另一种选择)作为路径分隔符。下面是一个非regexp版本的额外乐趣:

var leafname= pathname.split('\\').pop().split('/').pop();

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

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

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

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

return fullPath.replace(/^.*(\\|\/|\:)/, '');
<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 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>

完整的答案是:

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

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

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

var file_name = file_path.substring(file_path.lastIndexOf('/'));

为了提高性能,我测试了这里给出的所有答案:

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

获胜者是分开拆装风格的答案,感谢bobince !

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

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

在Node.js中,你可以使用路径的解析模块

var path = require('path');
var file = '/home/user/dir/file.txt';


var filename = path.parse(file).base;
//=> 'file.txt'

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

<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">

< br >

<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 lastPart = path.replace(/\\$/,'').split('\\').pop();

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

在你的项目中包含一个小函数,从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)
}

另一个

var filename = fullPath.split(/[\\\/]/).pop();
这里分裂有一个带有字符类
的正则表达式 这两个字符必须用'\'

转义

或者使用要分割的数组

var filename = fullPath.split(['/','\\']).pop();
如果需要,这是动态地将更多分隔符推入数组的方法 如果fullPath是由代码中的字符串显式设置的,则需要转义反斜杠!< br > 像"C:\\Documents and Settings\\img\\recycled log.jpg" < / p >

这个解决方案对'fileName'和'path'都更简单和通用。

parsePath = (path) => {
// regex to split path (untile last / or \ to two groups '(.*[\\\/])' for path and '(.*)' (untile the end after the \ or / )for file name
const regexPath = /^(?<path>(.*[\\\/])?)(?<filename>.*)$/;


const match = regexPath.exec(path);
if (path && match) {
return {
path: match.groups.path,
filename: match.groups.filename
}
}
throw Error("Error parsing path");
}


// example
const str = 'C:\\Documents and Settings\\img\\recycled log.jpg';
parsePath(str);

不需要专门处理反斜杠;大多数答案不处理搜索参数。

现代的方法是简单地使用URL API并获得pathname属性。API将反斜杠规范化为斜杠。注意,location(在浏览器环境中)也可以工作,但只适用于当前的 URL,而不是任意URL。

为了将结果%20解析为空格,只需将其传递给decodeURIComponent

const getFileName = (fileName) => new URL(fileName).pathname.split("/").pop();


// URLs need to have the scheme portion, e.g. `file://` or `https://`.
console.log(getFileName("file://C:\\Documents and Settings\\img\\recycled log.jpg")); // "recycled%20log.jpg"
console.log(decodeURIComponent(getFileName("file://C:\\Documents and Settings\\img\\recycled log.jpg"))); // "recycled log.jpg"
console.log(getFileName("https://example.com:443/path/to/file.png?size=480")); // "file.png"
.as-console-wrapper { max-height: 100% !important; top: 0; }

Add a .filter(Boolean) before the .pop() if you always want the last non-empty part of the path (e.g. file.png from https://example.com/file.png/).

If you only have a relative URL but still simply want to get the file name, use the second argument of the URL constructor to pass a base origin. "https://example.com" suffices: new URL(fileName, "https://example.com"). It’s also possible to prepend "https://" to your fileName — the URL constructor accepts https://path/to/file.ext as a valid URL.

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

function pathInfo(s) {
s=s.match(/(.*?[\\/:])?(([^\\/:]*?)(\.[^\\/.]+?)?)(?:[?#].*)?$/);
return {path:s[1],file:s[2],name:s[3],ext:s[4]};
}


console.log( pathInfo('c:\\folder\\file.txt') );


console.log( pathInfo('/folder/another/file.min.js?query=1') );
Type and try it:
<input oninput="document.getElementById('test').textContent=pathInfo(this.value).file" value="c:\folder\folder.name\file.ext" style="width:300px">

在Node.js中,你可以使用path.basename方法 .js

const path = require('path');
const file = '/home/user/dir/file.txt';


const filename = path.basename(file);
//=> 'file.txt'