tags:

views:

77

answers:

3

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 application name like in my case /AppName.

document.domain is returning the hostname and document.URL is returning the whole Url.

EDIT

Thr app path could be more complex, like /one/two/thre/

+1  A: 
(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.

Šime Vidas
Returns an error. 'pathName' should be all lowercase. It also doesn't satisfy the app path based on update to original question (otherwise a very smart solution).
michael
Yes, of course ... lowercase. However, it does not throw an error, but returns undefined.
Šime Vidas
I updated the code. Now it is in form of an function expression that executes and returns the desired string value...
Šime Vidas
+2  A: 

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 'thre'
// var path.join('/'); //  if you want the whole thing like '/one/two/thre/'
console.log(app);
michael
That will work fine, as long as the page is not served from a default document: `http://192.168.1.2/AppName/`
Daniel Vassallo
You're right. I've updated the code. However it only covers '.html' and would have to be modified if you have a different extension. Maybe having it look for '.' would be enough for most people?
michael
+1  A: 

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());
irishbuzz