Search code examples
javascriptjqueryarraysstring

Get all parent paths from Path String - Javascript


I need some advice concerning string manipulation. This is a possible string:

"/branches/projects/MyTool/MyTool/someOtherFolderOrFile"

What I need is an array with the following in it:

 ['/branches', '/branches/projects','/branches/projects/MyTool','/branches/projects/MyTool/MyTool']

So to clarify what this array should contain: All parent paths to the last file or folder. The last file or folder is excluded in the array.

I know I can split the string at "/" and then could iterate over the array, concatenate strings and delete the last entry from the array. This method I would call recursively until there is no element in the array left. The concatenated string would then be saved at every iteration to a new array which would hold the desired result at the end......

However I asked me how to do it very clean and simple and I am sure someone of you can come up with a superb solution :)

EDIT Here is my current solution I came up with just now:

var string = "/branches/projects/MyTool/MyTool/anotherFolderOrFile";
var helperArr = string.split("/");
var endArray = [];

getParentArray();
console.log(endArray);

function getParentArray() {
    if(helperArr.length == 1) {
        return;
    }
    else {
        var helperString = "";
        for(var i = 0;i<helperArr.length;i++) {
            helperString = helperString+helperArr[i];
            if(i!= helperArr.length -1) {
                helperString = helperString+"/";
            }
        }
        endArray.push(helperString);
        helperArr.length = helperArr.length-1;
        getParentArray();
    }
}

Solution

  • This will do the trick:

    /* First split the path at any folders separator ('/')*/
    var splitPath = "/branches/projects/MyTool/MyTool/someOtherFolderOrFile".split("/");
    /* Initialise a final array to save the paths. Store the first one in there! */
    var endPaths = [splitPath[0] + "/"];
    /* Check if there are multiple paths available */
    if(splitPath.length >= 2){
        /* Run through each and append it to the last saved one, then add it to the results.*/
        for(var i = 1; i <= splitPath.length-1; i++){
            endPaths.push(endPaths[i-1] + splitPath[i] + "/")
        }
    }
    

    This will include / as a path, which is technically a path. If you don't want that, you can use this line instead at the initialisation to exclude any simple paths like that:

    var endPaths = splitPath[0] != "" ? [splitPath[0] + "/"] : [];
    

    If you do the above though, beware that your loop will throw an error as endPaths[i-1] will be undefined when your loop starts running, you will have to do a check inside your for loop:

    /* You need to do -2 as you start at 1, but you only want to add paths from 2 upwards.*/
    var prevPath = typeof endPaths[i-2] !== "undefined" ? endPaths[i-2] : "";
    endPaths.push(prevPath + splitPath[i] + "/")