How to get the file name from a full path using JavaScript?

前端 未结 18 938
生来不讨喜
生来不讨喜 2020-11-22 11:01

Is there a way that I can get the last value (based on the \'\\\' symbol) from a full path?

Example:

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

相关标签:
18条回答
  • 2020-11-22 11:33

    Just for the sake of performance, I tested all the answers given here:

    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
    

    And the winner is the Split and Pop style answer, Thanks to bobince !

    0 讨论(0)
  • 2020-11-22 11:36

    This solution is much simpler and generic, for both 'file name' and 'path'.

    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];
    }
    
    0 讨论(0)
  • 2020-11-22 11:37

    Successfully Script for your question ,Full Test

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

    0 讨论(0)
  • 2020-11-22 11:40

    What platform does the path come from? Windows paths are different from POSIX paths are different from Mac OS 9 paths are different from RISC OS paths are different...

    If it's a web app where the filename can come from different platforms there is no one solution. However a reasonable stab is to use both '\' (Windows) and '/' (Linux/Unix/Mac and also an alternative on Windows) as path separators. Here's a non-RegExp version for extra fun:

    var leafname= pathname.split('\\').pop().split('/').pop();
    
    0 讨论(0)
  • 2020-11-22 11:40
    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(".") );
    }
    
    0 讨论(0)
  • 2020-11-22 11:44

    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(/^.*(\\|\/|\:)/, '');
    
    0 讨论(0)
提交回复
热议问题