Brian's Blog

items I see across my tribes

How to get the root domain in JavaScript

May 04
by briancarter 4. May 2009 08:10

I was looking for a way to get the root domain name of any URL, through use of JavaScript.  I often use Cassani for local development and run into the issue of the port and application name when trying to set the image location to a folder off the root such as: “lightbox/images”. 

I updated a function that I use to consider if the app is running in Cassani or not.  If not, just grab the URL.  If it is running on localhost, include the application name too.

function getRootURL() {
    var baseURL = location.href;
    var rootURL = baseURL.substring(0, baseURL.indexOf('/', 7));

    // if the root url is localhost, don't add the directory as cassani doesn't use it
    if (baseURL.indexOf('localhost') == -1) {
        return rootURL + "/";
    } else {
    return rootURL + baseURL.substring(baseURL.indexOf('/', 8), baseURL.indexOf('/', baseURL.indexOf('/', 8)+1)) + "/";        
    }
}

A little environment transparency. 

Categories: Development

Comments

Add comment




  Country flag

biuquote
  • Comment
  • Preview
Loading




 Questions or Feedback, my contact information is located on my About page.


The opinions, thoughts, and comments made in these blog posts are solely my own (unless otherwise stated). They do not reflect the opinions, thoughts or practices of my employer, my universities, my family, or anyone else. Also, I retain the right to change my mind about anything I publish here without having to go back and edit posts that occurred in the past. 

These are my opinions, or just as likely, someone else's opinions that I leveraged for my own.