在js

时间:2018-01-09 09:08:49

标签: javascript

需要JavaScript中的方法来提取文件名和扩展名。

实施例: /vagrant/modules/americabuy/tranzilaNotifications/class/../../../a_tranzila/log/tranzila_2018-01-09_08-58-47.json

返回数组:["tranzila_2018-01-09_08-58-47","json"]

5 个答案:

答案 0 :(得分:3)

在Node.js

var path = require('path');

function getFilenameAndExtension(pathfilename){
    return [path.parse(pathfilename).name, path.parse(pathfilename).ext];
}

在JavaScript中

function getFilenameAndExtension(pathfilename){

  var filenameextension = pathfilename.replace(/^.*[\\\/]/, '');
  var filename = filenameextension.substring(0, filenameextension.lastIndexOf('.'));
  var ext = filenameextension.split('.').pop();

  return [filename, ext];

}

Reuslt

getFilenameAndExtension("/vagrant/modules/americabuy/tranzilaNotifications/class/../../../a_tranzila/log/tranzila_2018-01-09_08-58-47.json");
//Result -> ["tranzila_2018-01-09_08-58-47", "json"]

答案 1 :(得分:1)

您可以使用split()功能与pop()结合使用来获取文件全名(名称+扩展名),并使用lastIndexOf()检测文件名和扩展名之间的分隔:



var str = '/vagrant/modules/americabuy/tranzilaNotifications/class/../../../a_tranzila/log/tranzila_2018-01-09_08-58-47.json';

function fileNameAndExt(str){
  var file = str.split('/').pop();
  return [file.substr(0,file.lastIndexOf('.')),file.substr(file.lastIndexOf('.')+1,file.length)]
}

console.log(fileNameAndExt(str));




答案 2 :(得分:0)

不需要复杂的事情。 您在Javascript中使用split(" ")方法可以执行您想要的操作。

var str = '/vagrant/modules/americabuy/tranzilaNotifications/class/../../../a_tranzila/log/tranzila_2018-01-09_08-58-47.json';

var file = str.split('/').pop();
var fileAndExtensionArray = file.split(".");  // This is ["tranzila_2018-01-09_08-58-47","json"]

答案 3 :(得分:0)

String.prototype.match()解决方案:

var filepath = '/vagrant/modules/americabuy/tranzilaNotifications/class/../../../a_tranzila/log/tranzila_2018-01-09_08-58-47.json',
    result = (m = filepath.match(/([^/]+)\.([^.]+)$/)) && m.slice(1,3);
    
console.log(result);

答案 4 :(得分:0)

var filepath =&#39; / vagrant / modules / americabuy / tranzilaNotifications / class /../../../ a_tranzila / log / tranzila_2018-01-09_08-58-47.json&#39;; < / p>

var filename = filepath.split(&#34;&#34;)[filepath.length-1];

var extension = filename.split(&#34;。&#34;)[filename.length-1];