Как получить имя файла из полного пути с помощью JavaScript?



есть ли способ, которым я могу получить последнее значение (на основе символа'') из полного пути?



пример:



C:Documents and Settingsimgrecycled log.jpg



в этом случае я просто хочу получить recycled log.jpg из полного пути в JavaScript.

374   17  

17 ответов:

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

и победителем становится Сплит и поп стиль ответа, благодаря bobince !

С какой платформы идет путь? Пути Windows отличаются от путей POSIX отличаются от путей Mac OS 9 пути отличаются от путей RISC OS отличаются...

Если это веб-приложение, где имя файла может поступать с разных платформ, нет одного решения. Однако разумным ударом является использование как " \ "(Windows), так и " / " (Linux/Unix/Mac, а также альтернатива в Windows) в качестве разделителей путей. Вот версия без регулярных выражений для дополнительного удовольствия:

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

В Узел.JS, вы можете использовать модуль синтаксического анализа пути...

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

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

АТЭЦ, ваше решение не защищает от пустой строки в качестве входных данных. В этом случае он терпит неудачу с 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);

не более лаконично, чем у никфа ответ, но этот непосредственно "извлекает" ответ вместо замены ненужных частей пустой строкой:

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

вопрос, задающий "получить имя файла без расширения", см. здесь, но для этого нет решения. Вот решение, измененное из решения Бобби.

var name_without_ext = (file_name.split('\').pop().split('/').pop().split('.'))[0];
<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>

Я использую:

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

Он заменяет последний \ так он также работает с папками.

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

небольшая функция для включения в ваш проект, чтобы определить имя файла из полного пути для 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 file_name = file_path.substring(file_path.lastIndexOf('/'));

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(".") );
}
<script type="text\javascript">   
   var path = '<%=Request.Url.GetLeftPart(UriPartial.Authority) + Request.ApplicationPath %>';
</script>

см. от http://www.codeprojectdownload.com

Comments

    Ничего не найдено.