是否有一种方法,我可以得到的最后一个值(基于'\'符号)从一个完整的路径?

例子:

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

在这种情况下,我只想从JavaScript的完整路径中回收log.jpg。


当前回答

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

其他回答

下面这行JavaScript代码将提供文件名。

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

Ates,您的解决方案不能防止空字符串作为输入。在这种情况下,它失败的TypeError: /([^(\\|\/|\:)]+)$/.exec(fullPath)没有属性。

这是nickf's的一个版本,它处理DOS, POSIX和HFS路径分隔符(和空字符串):

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

这将处理两个\ OR / in路径

这个解决方案对'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);

一个简单的函数,如PHP pathInfo:

函数pathInfo(s) { s = s.match (/(.*?[\\/:])?(([^\\/:]*?)(\.[^\\/.]+?)?)(?:[?#].*)?$/); {返回文件路径:s[1]:[2],名字:[3],ext: s [4]}; } console.log(pathInfo('c:\\文件夹\\文件.txt')); console.log(pathInfo('/folder/another/file.min.js?query=1')); 输入并尝试一下: <输入oninput = " . getelementbyid(“测试”).textContent = pathInfo (this.value)。文件" value="c:\folder\folder.name\ File .ext" style="width:300px">