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

前端 未结 18 941
生来不讨喜
生来不讨喜 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:47

    The following line of JavaScript code will give you the file name.

    var z = location.pathname.substring(location.pathname.lastIndexOf('/')+1);
    alert(z);
    
    0 讨论(0)
  • 2020-11-22 11:47

    A question asking "get file name without extension" refer to here but no solution for that. Here is the solution modified from Bobbie's solution.

    var name_without_ext = (file_name.split('\\').pop().split('/').pop().split('.'))[0];
    
    0 讨论(0)
  • 2020-11-22 11:48
    <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>
    
    0 讨论(0)
  • 2020-11-22 11:49

    In Node.js, you can use Path's parse module...

    var path = require('path');
    var file = '/home/user/dir/file.txt';
    
    var filename = path.parse(file).base;
    //=> 'file.txt'
    
    0 讨论(0)
  • 2020-11-22 11:50

    Another one

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

    Here split have a regular expression with a character class
    The two characters have to be escaped with '\'

    Or use array to 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"

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

    I use:

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

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

    0 讨论(0)
提交回复
热议问题