Search code examples
javascriptjqueryajaxlastindexof

How do you determine the current directory in a path string?


The Question: How do you determine a variable length string inbetween two similar characters?

Allow me to clarify:

take the two URLs:

/designs/2012/mobile/v4/~html/ecom/

/designs/2012/mobile/v4/~html/legal/

I'm trying to build an anchor with an ID that equals the name of each line's current directory: ecom, legal, local, etc.

So the above directories would result in a page with the following:

<a href="/designs/2012/mobile/v4/~html/ecom/" id="ecom">/designs/2012/mobile/v4/~html/ecom/</a>
<a href="/designs/2012/mobile/v4/~html/legal/" id="legal">/designs/2012/mobile/v4/~html/legal/</a>

I've been playing around with .lastIndexOf but am having little luck. I figured if I could say (warning psuedo-code ahead!) "get the 2nd to last / and pull the string inbetween that and the last /" but I'm not quite sure how to do that.

Any tips or pointers?

Here's my code thus far:

$(document).ready(function() {
$.ajax({
    url: "./~html",
    success: function(data){
        $(data).find("a").each(function(){
            var path = $(this).attr("href");
            var fileNameIndex = path.lastIndexOf("/") + 1;
            var dirNameIndex = path.lastIndexOf("/");
            var dirNameLength = path.length -1;
            var file = path.substr(fileNameIndex);
            var directory = path.substr(dirNameIndex);
            console.log("length of string: " + dirNameLength);
            console.log("Directory Index: " + dirNameIndex);
            console.log(directory);
            var idIndex = 1;

            if (file != "") {
                $('<li></li>').html('<a href=\"' + path + '\">' + file + '</a>').appendTo('#files');
            } else {
                $('<li></li>').html('<a href=\"' + path + '\"' + 'id=\"' + directory + '\">' + path + '</a>').appendTo('#directories');
            }

        });
    }
});

});


Solution

  • One possible way is by splitting the string by slash into an array:

    var path = '/designs/2012/mobile/v4/~html/ecom/';
    var components = path.split('/');
    var last_part = components[components.length-2];
    alert(last_part); // alerts 'ecom'
    

    path.split('/') will give you an array of 8 items (components.length is 8):

    components[0] = '';
    components[1] = 'designs';
    components[2] = '2012';
    components[3] = 'mobile';
    components[4] = 'v4';    
    components[5] = '~html';
    components[6] = 'ecom';
    components[7] = '';