我正在寻找一些帮助,我是新手学习Javascript,我想删除路径中的最后一个文件夹名称。
示例:/FOLDER1/FOLDER2/FOLDER3/
是我当前的路径,我想得到像/FOLDER1/FOLDER2/
这样的结果
多谢。
var path = '/FOLDER1/FOLDER2/FOLDER3/';
var splitPath = path.split('/');//[0] = '', [1] = FOLDER1, [2] = FOLDER2, [3] = FOLDER3
var finalPath = "/" + splitPath[1]+ "/"+ splitPath[2] + "/";
试试这个
var path = '/FOLDER1/FOLDER2/FOLDER3/';
var splitPath = path.split('/'); // ["", "FOLDER1", "FOLDER2", "FOLDER3", ""]
splitPath.shift(); // ["FOLDER1", "FOLDER2", "FOLDER3", ""]
splitPath.pop(); // ["FOLDER1", "FOLDER2", "FOLDER3"]
splitPath.pop(); // ["FOLDER1", "FOLDER2"]
var result = "/" + splitPath.join("/") + "/"; // "/FOLDER1/FOLDER2/"
console.log(result);
这是另一种方式:
'/FOLDER1/FOLDER2/FOLDER3/'.replace(/(w*/)$/, '');
//gives you: "/FOLDER1/FOLDER2/"
再来一个:
var s = "FOLDER1/FOLDER2/FOLDER3/";
var ss = s.replace(//$/, '');
ss.substring(0, ss.lastIndexOf('/'));
另一个:
const [path1, path2] = "FOLDER1/FOLDER2/FOLDER3/".split("/")
console.log('path: ', `/${path1}/${path2}/`);
另一个:
var s = "FOLDER1/FOLDER2/FOLDER3/";
const [newPath] = s.split(/(w+/)$/)
//"FOLDER1/FOLDER2/"
let path = "/FOLDER1/FOLDER2/FOLDER3/"
let result = path.split("/").filter((el,idx, arr) => idx < arr.length - 2).join("/") + "/"
console.log(result)