Search code examples
javascriptpathlocationpathname

Comparing paths


In my function user inputs a path like './images/profile' and i need to check whether the current path of the page is same as the path he passed. I. e. check whether path == location.pathname.

if location.pathname is /scripts and the path entered ./../parent/scripts where parent is parent directory of scripts, the comparison should return true and it should return false if path entered is ./../parent/images etc. So is there any method in JS to comapre two paths?


Solution

  • var p = currentpath + inputpath;
    var frags = p.split("/");
    for (var i=0; i<frags.length; i++) {
        if (i>0 && frags[i] == "..") {
            frags.splice(i-1, 2);
            i -= 2;
        } else if (!frags[i] && frags[i][0] == ".") { // removes also three or more dots
            frags.splice(i, 1);
            i--;
        }
    }
    return frags.join("/") == suggestedpath;
    

    should do the task. Maybe a regexp would be shorter, but it doesn't allow navigation in Arrays :-)