2

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.

Charles
  • 50,943
  • 13
  • 104
  • 142
sarsnake
  • 26,667
  • 58
  • 180
  • 286

3 Answers3

6

Yes: window.location.hostname

Audun Larsen
  • 958
  • 5
  • 7
  • While this works for this specific question (root guaranteed to be equal to host name), it doesn't address how to directly get the root URL in other cases. – Sam Dec 20 '13 at 03:30
3

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'

Community
  • 1
  • 1
2

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.

Usage:

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
Community
  • 1
  • 1
Mephiztopheles
  • 2,228
  • 1
  • 12
  • 25