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

2020/10/02 19:41 · javascript ·  · 0评论

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

例:

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

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

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

这将处理路径中的\ OR /

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

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的parse模块...

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

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

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

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

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

Ates, your solution doesn't protect against an empty string as input. In that case, it fails with TypeError: /([^(\\|\/|\:)]+)$/.exec(fullPath) has no properties.

bobince, here's a version of nickf's that handles DOS, POSIX, and HFS path delimiters (and empty strings):

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

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

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

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

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

询问“获取不带扩展名的文件名”的问题是在这里,但没有解决方案。这是Bobbie解决方案修改后的解决方案。

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

另一个

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

这里split具有一个带有字符类

正则表达式两个字符必须用'\'进行转义

或使用数组拆分

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

It would be the way to dynamically push more separators into an array, if needed.
If fullPath is explicitly set by a string in your code it need to escape the backslash!
Like "C:\\Documents and Settings\\img\\recycled log.jpg"

I use:

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

It replaces the last \ so it also works with folders.

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

完整的答案是:

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

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

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];
}
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('/'));

本文地址:http://javascript.askforanswer.com/ruheshiyongjavascriptcongwanzhenglujinghuoquwenjianming.html
文章标签:
版权声明:本文为原创文章,版权归 javascript 所有,欢迎分享本文,转载请保留出处!

文件下载

老薛主机终身7折优惠码boke112

上一篇:
下一篇:

评论已关闭!