【发布时间】:2010-09-30 05:13:45
【问题描述】:
有没有办法从完整路径中获取最后一个值(基于“\”符号)?
例子:
C:\Documents and Settings\img\recycled log.jpg
在这种情况下,我只想从 JavaScript 的完整路径中获取recycled log.jpg。
【问题讨论】:
标签: javascript
有没有办法从完整路径中获取最后一个值(基于“\”符号)?
例子:
C:\Documents and Settings\img\recycled log.jpg
在这种情况下,我只想从 JavaScript 的完整路径中获取recycled log.jpg。
【问题讨论】:
标签: javascript
var filename = fullPath.replace(/^.*[\\\/]/, '')
这将同时处理路径中的 \ 或 /
【讨论】:
replace比substr慢很多,可以和lastIndexOf('/')+1配合使用:jsperf.com/replace-vs-substring
"/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's parse module...
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 路径不同...
如果它是一个文件名可以来自不同平台的网络应用程序,那么没有一个解决方案。然而,合理的做法是同时使用 '\' (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,这是处理 DOS、POSIX 和 HFS 路径分隔符(和空字符串)的 nickf 版本:
return fullPath.replace(/^.*(\\|\/|\:)/, '');
【讨论】:
以下 JavaScript 代码行将为您提供文件名。
var z = location.pathname.substring(location.pathname.lastIndexOf('/')+1);
alert(z);
【讨论】:
另一个
var filename = fullPath.split(/[\\\/]/).pop();
这里split 有一个带有character class 的正则表达式
这两个字符必须用'\'转义
或者使用array to split
var filename = fullPath.split(['/','\\']).pop();
如果需要,这将是动态将更多分隔符推入数组的方法。
如果 fullPath 由代码中的字符串显式设置,则需要 escape the backslash!
赞"C:\\Documents and Settings\\img\\recycled log.jpg"
【讨论】:
.split(['/','\\']) 和.split("/,\\") 一样,这绝对不是你想要的。
没有比 nickf 的 answer 更简洁,但是这个直接“提取”了答案,而不是用空字符串替换不需要的部分:
var filename = /([^\\]+)$/.exec(fullPath)[1];
【讨论】:
不需要专门处理反斜杠;大多数答案不处理搜索参数。
现代方法是简单地使用URL API 并获取pathname 属性。 API 将反斜杠规范化为斜杠。
要将生成的%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; }
如果您总是希望路径的最后一个非空部分(例如file.png 来自https://example.com/file.png/),请在.pop() 之前添加.filter(Boolean)。
如果您只有相对 URL,但仍只想获取文件名,请使用 second argument of the URL constructor 传递基本来源。 "https://example.com" 足够了:new URL(fileName, "https://example.com")。也可以将 "https://" 添加到您的 fileName — URL 构造函数接受 https://path/to/file.ext 作为有效 URL。
【讨论】:
询问“获取不带扩展名的文件名”的问题请参阅此处,但没有解决方案。 这是从 Bobbie 的解决方案修改而来的解决方案。
var name_without_ext = (file_name.split('\\').pop().split('/').pop().split('.'))[0];
【讨论】:
我使用:
var lastPart = path.replace(/\\$/,'').split('\\').pop();
它替换了最后一个 \,因此它也适用于文件夹。
【讨论】:
<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>
【讨论】:
在您的项目中包含一个小函数,用于根据 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)
}
【讨论】:
对于“文件名”和“路径”,此解决方案更加简单和通用。
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);
【讨论】:
完整的答案是:
<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>
【讨论】:
<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)
}
【讨论】:
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">
【讨论】:
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('/'));
【讨论】: