itsource

JavaScript를 사용하여 전체 경로에서 파일 이름을 가져오려면 어떻게 해야 합니까?

mycopycode 2022. 9. 17. 09:58
반응형

JavaScript를 사용하여 전체 경로에서 파일 이름을 가져오려면 어떻게 해야 합니까?

전체 경로에서 마지막 값('\' 기호 기준)을 가져올 수 있는 방법이 있습니까?

예제:

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

그리고 우승자는 'Thanks to bobince'라는 Split and Pop 스타일의 답변입니다.

Node.js에서는 Path의 해석 모듈을 사용할 수 있습니다.

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 패스는 다릅니다.

다른 플랫폼에서 파일 이름을 가져올 수 있는 웹 앱이라면 하나의 해결책이 없습니다.단, 패스 구분자로 '\'(Windows)와 '/'(Linux/Unix/Mac 및 Windows의 대체)를 모두 사용하는 것이 합리적입니다.RegExp 이외의 버전은 다음과 같습니다.

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

즉, 입력 문자열이 빈 경우 솔루션이 보호하지 않습니다.이 경우 에러가 발생합니다.TypeError: /([^(\\|\/|\:)]+)$/.exec(fullPath) has no properties.

다음은 DOS, POSIX 및 HFS 경로 구분자(및 빈 문자열)를 처리하는 nickf 버전입니다.

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

다음 줄의 JavaScript 코드가 파일 이름을 제공합니다.

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

하나 더

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

여기서 분할은 문자 클래스가 있는 정규 표현식을 가집니다.
두 문자는 '\'로 이스케이프해야 합니다.

또는 어레이를 사용하여 분할

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

필요한 경우 어레이에 더 많은 분리기를 동적으로 푸시할 수 있습니다.
한다면fullPath코드 내의 문자열에 의해 명시적으로 설정되어 있기 때문에 백슬래시를 이스케이프 할 필요가 있습니다.
맘에 들다"C:\\Documents and Settings\\img\\recycled log.jpg"

nickf의 답변보다 간결하지는 않지만, 이 답변은 불필요한 부분을 빈 문자열로 대체하는 대신 직접 "추출"됩니다.

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

백슬래시를 특별히 처리할 필요는 없습니다.대부분의 응답은 검색 파라미터를 처리하지 않습니다.

현대적 접근법은 API를 단순히 사용하고, 이 API를 사용하여pathname소유물.API는 백슬래시를 슬래시로 정규화합니다.

결과를 해석하려면%20에 전달하기만 하면 됩니다.

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만 있고 파일 이름을 가져오려면 생성자의 번째 인수를 사용하여 기본 오리진을 전달합니다. "https://example.com"다음과 같이 입력합니다.new URL(fileName, "https://example.com") 요."https://"your fileNameURL는 ""를 받아들인다"https://path/to/file.ext【URL】【URL】

"확장자 없이 파일 이름 가져오기"라는 질문은 여기서 언급되지만 이에 대한 해결책은 없습니다.다음은 Bobbie의 솔루션에서 변경된 솔루션입니다.

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

사용방법:

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

을 대신합니다.\폴더도 사용할 수 있습니다.

Node.js에서는 다음 방법을 사용할 수 있습니다.

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

const filename = path.basename(file);
//=> 'file.txt'

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

이 솔루션은 'fileName'과 'path' 모두에서 훨씬 단순하고 일반적입니다.

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

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

언급URL : https://stackoverflow.com/questions/423376/how-to-get-the-file-name-from-a-full-path-using-javascript

반응형