如何使用JavaScript从完整路径获取文件名?

问题描述 投票:0回答:22

有没有办法可以从完整路径获取最后一个值(基于“\”符号)?

示例:

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

在这种情况下,我只想从 JavaScript 中的完整路径中获取

recycled log.jpg

javascript
22个回答
877
投票
var filename = fullPath.replace(/^.*[\\/]/, '')

这将处理路径中的 / 或 \ 。


204
投票

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

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


187
投票

在 Node.js 中,要获取基本名称,您可以使用 Path 的模块

basename
函数:

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

如果您要对文件执行更多操作,您可能需要使用 Path 的

parse
函数:

var details = path.parse(file);
//=> { root: '/', dir: '/home/user/dir', base: 'file.txt', ext: '.txt', name: 'file' }
var name = details.base
//=> 'file.txt'

94
投票

路径来自什么平台? Windows 路径不同于 POSIX 路径不同于 Mac OS 9 路径不同于 RISC OS 路径不同...

如果它是一个文件名可能来自不同平台的网络应用程序,则没有一种解决方案。然而,合理的做法是使用“\”(Windows)和“/”(Linux/Unix/Mac 以及 Windows 上的替代方案)作为路径分隔符。这是一个非 RegExp 版本,带来额外的乐趣:

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

33
投票

Ates,您的解决方案无法防止输入空字符串。 在这种情况下,它会失败并显示

TypeError: /([^(\\|\/|\:)]+)$/.exec(fullPath) has no properties

bobince,这是 nickf 的一个版本,可以处理 DOS、POSIX 和 HFS 路径分隔符(和空字符串):

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

26
投票

以下 JavaScript 代码行将为您提供文件名。

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

15
投票

另一个

var filename = fullPath.split(/[\\\/]/).pop();

这里 split 有一个带有 字符类
的正则表达式 这两个字符必须用 '\' 转义

或者使用数组来分割

var filename = fullPath.split(['/','\\']).pop();

如果需要,这将是动态地将更多分隔符推入数组的方法。
如果

fullPath
是由代码中的字符串显式设置的,则需要 转义反斜杠
喜欢
"C:\\Documents and Settings\\img\\recycled log.jpg"


14
投票

在 Node.js 中,您可以使用

path.basename
方法

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

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

13
投票

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

现代方法是简单地使用

URL
API 并获取
pathname
属性。 API 将反斜杠规范化为斜杠。请注意,
location
(在浏览器环境中)也适用,但仅适用于 current 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; }

如果您始终想要路径的最后一个

非空
部分(例如来自
.filter(Boolean)
.pop()),请在
file.png
之前添加
https://example.com/file.png/

如果您只有相对 URL,但仍只想获取文件名,请使用 URL

 构造函数
的第二个参数来传递基本原点。 "https://example.com"
就足够了:
new URL(fileName, "https://example.com")
。也可以将 
"https://"
 添加到 
fileName
  —  
URL
 构造函数接受 
https://path/to/file.ext
 作为有效 URL。


10
投票
并不比nickf的

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

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

9
投票
询问“获取不带扩展名的文件名”的问题请参阅此处,但没有解决方案。 这是从 Bobbie 的解决方案修改而来的解决方案。

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

4
投票
我用:

var lastPart = path.replace(/\\$/,'').split('\\').pop();

它取代了最后一个

\

,因此它也适用于文件夹。


4
投票
对于“文件名”和“路径”,此解决方案更加简单和通用。

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


3
投票
项目中包含的小函数,用于从 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) }
    

2
投票
<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>
    

1
投票
完整答案是:

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

1
投票
像 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">


0
投票
<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>
    

0
投票
成功为您的问题编写脚本,完整测试

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


0
投票
使用子字符串替换速度较慢

var fileName = fullPath.substring(fullPath.lastIndexOf('\\')+1);
注意:如果您想从输入字段获取,则可以通过以下简单代码直接获取(如果选择了任何文件)。假设 id="file"

var fileName = document.getElementById('file').files[0].name;
    

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

-3
投票

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


    

© www.soinside.com 2019 - 2024. All rights reserved.