开发者

String to array then remove last element

开发者 https://www.devze.com 2023-03-29 16:52 出处:网络
I have the strings below and I am trying to remove the last directory from them but I cant seem to get the grasp of it.

I have the strings below and I am trying to remove the last directory from them but I cant seem to get the grasp of it.

JavaScript

var x = path.split("/")
alert(path +' = ' +x.slice(0, -1));

Expected Result

/foo/bar/ = /foo/
/bar/foo/ = /bar/
/bar/foo/m开发者_运维问答oo/ = /bar/foo/


Try:

let path = "/bar/foo/moo/";
let split = path.split("/");
let splicedStr = split.slice(0, split.length - 2).join("/") + "/";
console.log(splicedStr);


Try:

var sourcePath="/abc/def/ghi";
var lastIndex=sourcePath.lastIndexOf("/");
var requiredPath=sourcePath.slice(0,lastIndex+1);

Output: /abc/def/

0

精彩评论

暂无评论...
验证码 换一张
取 消