say I'm developing a website.com. I need to get the root (website.com) dynamically (for dev and production). Is there a way to do it in JS?
I am using asp.net mvc 3 on the server.
say I'm developing a website.com. I need to get the root (website.com) dynamically (for dev and production). Is there a way to do it in JS?
I am using asp.net mvc 3 on the server.
See: How to extract the hostname portion of a URL in JavaScript
Quote from the link:
You could concatenate the location protocol and the host: var root = location.protocol + '//' + location.host; For a url, let say 'https://stackoverflow.com/questions', it will return 'http://stackoverflow.com'
I created a function to get real root:
function root() {
        var scripts = document.getElementsByTagName( 'script' ),
            script = scripts[scripts.length - 1],
            path = script.getAttribute( 'src' ).split( '/' ),
            pathname = location.pathname.split( '/' ),
            notSame = false,
            same = 0;
        for ( var i in path ) {
            if ( !notSame ) {
                if ( path[i] == pathname[i] ) {
                    same++;
                } else {
                    notSame = true;
                }
            }
        }
        return location.origin + pathname.slice( 0, same ).join( '/' );
    }
call this function once when the js-file is loaded.
to make it work, you MUST include it as js-file.
var basepath = root();
here are some examples:
location.host: 'http://test.com'
location.path: '/myapp/controller/action/id'
this will result in:
http://test.com/myapp