在 Node 中,如何删除以某些特定字符结尾的子字符串
in Node, how to remove a substring that ends with some certain characters
在sourceConfigPath变量中,它有一个像"conf/test.json"
这样的路径,或者它可能有另一个层,像"test/conf/test.json"
。我只想得到 "test.json"
部分。
我尝试使用 indexOf 函数获取位置,然后使用 slice 或 substr 函数获取 'test.json'
部分。但是当 indexOf
.
时总是 return 0
有人可以帮忙吗?非常感谢!
var position = sourceConfigPath.indexOf('conf');
var newsourceConfigPath = sourceConfigPath.slice(position+4);
或者有更好的方法吗?非常感谢!
最好的方法是使用path.basename
The path.basename() methods returns the last portion of a path,
similar to the Unix basename
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));
在sourceConfigPath变量中,它有一个像"conf/test.json"
这样的路径,或者它可能有另一个层,像"test/conf/test.json"
。我只想得到 "test.json"
部分。
我尝试使用 indexOf 函数获取位置,然后使用 slice 或 substr 函数获取 'test.json'
部分。但是当 indexOf
.
有人可以帮忙吗?非常感谢!
var position = sourceConfigPath.indexOf('conf');
var newsourceConfigPath = sourceConfigPath.slice(position+4);
或者有更好的方法吗?非常感谢!
最好的方法是使用path.basename
The path.basename() methods returns the last portion of a path, similar to the Unix basename
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));