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

如何使用JavaScript从完整路径获取文件名?,javascript,Javascript,有没有办法从完整路径中获取最后一个值(基于“\”符号) 例如: C:\Documents and Settings\img\recycled log.jpg 在本例中,我只想从JavaScript中的完整路径获取回收的log.jpg var filename = fullPath.replace(/^.*[\\\/]/, '') 这将处理\或/路径中的路径路径来自哪个平台?Windows路径不同于POSIX路径不同于Mac OS 9路径不同于RISC OS路径不同 如果它是一个文件名可以来自不

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

例如:

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

在本例中,我只想从JavaScript中的完整路径获取回收的log.jpg

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

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

路径来自哪个平台?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];

但是,您的解决方案不能防止将空字符串作为输入。在这种情况下,它会失败,出现
TypeError:/([^(\\\\\/\\\\:)]+)$/。exec(fullPath)没有属性

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


功能测试()
{
var path=“C:/es/h221.txt”;
var pos=path.lastIndexOf(path.charAt(path.indexOf(“:”)+1));
警报(“pos=”+pos);
var filename=path.substring(位置+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>

测试文件上传输入
函数replaceAll(txt,replace,with_this){
返回txt.replace(新的RegExp(replace,'g'),带有此项);
}
函数showSrc(){
document.getElementById(“myframe”).href=document.getElementById(“myfile”).value;
var theexa=document.getElementById(“myframe”).href.replace(“文件:///”,”);
var path=document.getElementById(“myframe”).href.replace(“文件:///”,“”);
var correctPath=replaceAll(路径,“%20”和“);
警报(正确路径);
}


下面一行JavaScript代码将为您提供文件名

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

var file\u name=file\u path.substring(file\u 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];
在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">



函数replaceAll(txt,replace,with_this){
返回txt.replace(新的RegExp(replace,'g'),带有此项);
}
函数showSrc(){
document.getElementById(“myframe”).href=document.getElementById(“myfile”).value;
var theexa=document.getElementById(“myframe”).href.replace(“文件:///”,”);
var path=document.getElementById(“myframe”).href.replace(“文件:///”,“”);
var correctPath=replaceAll(路径,“%20”和“);
警报(正确路径);
var filename=correctPath.replace(/^.[\\/]/,'')
$(“#FileNameShow”).text(文件名)
}
我使用:

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();
这里有一个带a的正则表达式
这两个字符必须用“\”转义

或使用

如果需要,这将是一种将更多分隔符动态推入阵列的方法。
如果
fullPath
是由代码中的字符串显式设置的,则需要

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

这个解决方案对于“文件名”和“路径”来说都非常简单和通用

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];
}

没有必要专门处理反斜杠;大多数答案不处理搜索参数

现代方法是简单地使用并获取
pathname
属性。API将反斜杠规范化为斜杠

要将结果
%20
解析为一个空格,只需将其传递给

const getFileName=(fileName)=>新URL(fileName).pathname.split(“/”.pop();
//URL需要有方案部分,例如`file://`或`https://`。
console.log(getFileName(“file://C:\\Documents and Settings\\img\\recycled log.jpg”);//“回收%20log.jpg”
console.log(decodeURIComponent(getFileName(“file://C:\\Documents and Settings\\img\\recycled log.jpg”));//“回收日志.jpg”
console.log(getFileName(“https://example.com:443/path/to/file.png?size=480")); // “file.png”

。作为控制台包装{max height:100%!important;top:0;}
您可能需要添加经典的MacOS(您可以使用pop()而不是reverse()[0]。它也会修改原始数组,但在您的情况下也可以。我想知道如何创建一个对应的数组来获取路径。类似于
var path='\\Dir2\\Sub1\\SubSub1';//path='/Dir2/Sub1/subsubsub1';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);
命名“leafname”源自目录/文件结构
<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();
/**
 * @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();
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];
}