在Node中,如何删除以某些特定字符结尾的子字符串

时间:2018-05-09 02:20:50

标签: node.js string indexof

在sourceConfigPath变量中,它有一个类似"conf/test.json"的路径,或者它可能有另一个层,如"test/conf/test.json"。我想只获得"test.json"部分。

我尝试使用indexOf函数来获取位置,然后使用slice或substr函数来获取'test.json'部分。但是当indexOf时它总是返回0。

有人可以帮忙吗?非常感谢!

var position = sourceConfigPath.indexOf('conf');
var newsourceConfigPath = sourceConfigPath.slice(position+4);

或者有更好的方法吗?非常感谢!

1 个答案:

答案 0 :(得分:3)

最好的方法是使用path.basename

  

path.basename()方法返回路径的最后一部分,   类似于Unix基本名称

const path = require('path');
const newSource = path.basename('conf/test.json'); // test.json

您可以使用lastIndexOf代替indexOf,但建议使用path.basename

const filepath = '/path/to/file.json';

const position = filepath.lastIndexOf('/') + 1;  // +1 is to remove '/'

console.log(filepath.substr(position));

相关问题