有没有办法可以从完整路径获取最后一个值(基于“\”符号)?
示例:
C:\Documents and Settings\img\recycled log.jpg
在这种情况下,我只想从 JavaScript 中的完整路径中获取
recycled log.jpg
。
var filename = fullPath.replace(/^.*[\\/]/, '')
这将处理路径中的 / 或 \ 。
只是为了性能,我测试了这里给出的所有答案:
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!
在 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'
路径来自什么平台? Windows 路径不同于 POSIX 路径不同于 Mac OS 9 路径不同于 RISC OS 路径不同...
如果它是一个文件名可能来自不同平台的网络应用程序,则没有一种解决方案。然而,合理的做法是使用“\”(Windows)和“/”(Linux/Unix/Mac 以及 Windows 上的替代方案)作为路径分隔符。这是一个非 RegExp 版本,带来额外的乐趣:
var leafname= pathname.split('\\').pop().split('/').pop();
Ates,您的解决方案无法防止输入空字符串。 在这种情况下,它会失败并显示
TypeError: /([^(\\|\/|\:)]+)$/.exec(fullPath) has no properties
。
bobince,这是 nickf 的一个版本,可以处理 DOS、POSIX 和 HFS 路径分隔符(和空字符串):
return fullPath.replace(/^.*(\\|\/|\:)/, '');
以下 JavaScript 代码行将为您提供文件名。
var z = location.pathname.substring(location.pathname.lastIndexOf('/')+1);
alert(z);
path.basename
方法
const path = require('path');
const file = '/home/user/dir/file.txt';
const filename = path.basename(file);
//=> 'file.txt'
不需要专门处理反斜杠;大多数答案不处理搜索参数。
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。
var name_without_ext = (file_name.split('\\').pop().split('/').pop().split('.'))[0];
var lastPart = path.replace(/\\$/,'').split('\\').pop();
它取代了最后一个
\
,因此它也适用于文件夹。
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);
/**
* @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)
}
<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>
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">
<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)
}
var fileName = fullPath.substring(fullPath.lastIndexOf('\\')+1);
注意:如果您想从输入字段获取,则可以通过以下简单代码直接获取(如果选择了任何文件)。假设 id="file"
var fileName = document.getElementById('file').files[0].name;
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(".") );
}
var file_name = file_path.substring(file_path.lastIndexOf('/'));