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

例子:

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

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


当前回答

一个简单的函数,如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">

其他回答

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

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

var file_name = file_path.substring(file_path.lastIndexOf('/'));

不需要专门处理反斜杠;大多数答案不处理搜索参数。

现代的方法是简单地使用URL API并获取pathname属性。API将反斜杠规范化为斜杠。注意,位置(在浏览器环境中)也可以工作,但仅适用于当前URL,而不是任意URL。

为了将结果%20解析为空格,只需将其传递给decodeURIComponent。

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

如果你总是想要路径的最后一个非空部分(例如,来自https://example.com/file.png/的file.png),在.pop()之前添加一个.filter(布尔值)。

如果您只有一个相对URL,但仍然只想获得文件名,则使用URL构造函数的第二个参数来传递基源。“https://example.com”足够:新的URL(文件名,“https://example.com”)。也可以在你的文件名前加上“https://”——URL构造函数接受https://path/to/file.ext作为有效的URL。

不是比nickf的回答更简洁,但是这个直接“提取”了答案,而不是用空字符串替换不需要的部分:

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

在您的项目中包含一个小函数,用于从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)
}