سؤال

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?

هل كانت مفيدة؟

المحلول

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 :-)

نصائح أخرى

There's no built-in way to compare or resolve paths. You'll have to resort to parsing the strings, or some kind of hack like loading the relative path in a hidden iframe and checking if its location.href is equal to the current window's location.href... not that I'm advocating that approach.

function comparePath(path1, path2) {
  var path1Dir = path1.substring(path1.lastIndexOf('/'));
  var path2Dir = path2.substring(path2.lastIndexOf('/'));
  return path1Dir == path2Dir;
}

You can get the result by calling: comparePath(path, location.pathname);

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top