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

例子:

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

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


当前回答

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

其他回答

为了提高性能,我测试了这里给出的所有答案:

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

最后的赢家是“分拆式”答案,感谢波波斯!

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

var z = location.pathname.substring(location.pathname.lastIndexOf('/')+1);
alert(z);
<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>

路径来自哪个平台?Windows路径不同POSIX路径不同Mac OS 9路径不同RISC OS路径不同…

如果它是一个web应用程序,文件名可以来自不同的平台,那么就没有一个解决方案。然而,一个合理的尝试是同时使用'\' (Windows)和'/' (Linux/Unix/Mac和Windows上的另一种选择)作为路径分隔符。下面是一个非regexp版本的额外乐趣:

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

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