Skip to content Skip to sidebar Skip to footer

How-to Get The Application Path Using Javascript

If I have my application hosted in a directory. The application path is the directory name. For example http://192.168.1.2/AppName/some.html How to get using javascript the applica

Solution 1:

window.location.pathname.substr(0, window.location.pathname.lastIndexOf('/'))

Solution 2:

This will give you a result but would have to be modified if you have more levels (see commented code).

var path = location.pathname.split('/');
if (path[path.length-1].indexOf('.html')>-1) {
  path.length = path.length - 1;
}
var app = path[path.length-2]; // if you just want 'three'
// var app = path.join('/'); //  if you want the whole thing like '/one/two/three'
console.log(app);

Solution 3:

This should do the trick

function getAppPath() {
    var pathArray = location.pathname.split('/');
    var appPath = "/";
    for(var i=1; i<pathArray.length-1; i++) {
        appPath += pathArray[i] + "/";
    }
    return appPath;
}

alert(getAppPath());

Solution 4:

(function(p) {
    var s = p.split("/").reverse();
    s.splice(0, 1);
    return s.reverse().join("/");
})(location.pathname)

This is an expression... just copy-paste it to the place where you need that string. Or put it in a variable, so that you can use it multiple times.

Solution 5:

alert("/"+location.pathname.split('/')[1]);

If your path is something like /myApp/...

or

function applicationContextPath() {
    if (location.pathname.split('/').length > 1)
        return"/" + location.pathname.split('/')[1];
    elsereturn"/";
}
alert(applicationContextPath);

Post a Comment for "How-to Get The Application Path Using Javascript"