Thursday, April 5, 2012

get root URL in javascript


is there a really easy way to turn document.location.href=="http://aaa.bbb.ccc.ddd.com/asdf/sadf/asdf/asdf/asdf/sadf.aspx?blah" into 'aaa.bbb.ccc.ddd.com'?



There's gotta be a JS function that does this reliably, but I can't find it.


Source: Tips4all

3 comments:

  1. Use document.location object and its host or hostname properties.

    alert(document.location.hostname); // alerts "stackoverflow.com"

    ReplyDelete
  2. You could concatenate the location protocol and the host:

    var root = location.protocol + '//' + location.host;


    For a url, let say 'http://stackoverflow.com/questions', it will return 'http://stackoverflow.com'

    ReplyDelete
  3. Try document.location.host or document.location.hostname?

    ReplyDelete