0

How to get base url in jQuery?

Think I am in http://localhost/test/test_controller/test's js file then I want to get only

/test

or

http://localhost/test/
Milina Udara
  • 597
  • 1
  • 9
  • 24
  • How do you define this "base" URL? Is it always the first directory in your URL, or do you have an application where this URL is defined? – Pekka Mar 05 '12 at 08:57
  • 1
    possible duplicate of [Find base name in URL in Javascript](http://stackoverflow.com/questions/1991608/find-base-name-in-url-in-javascript) – Yi Jiang Mar 05 '12 at 08:57

3 Answers3

9

You dont actually need to use jQuery. JavaScript provides this for you

var l = window.location;
var base_url = l.protocol + "//" + l.host + "/" + l.pathname.split('/')[1];
Greg Guida
  • 7,302
  • 4
  • 30
  • 40
  • 1
    That won't give the "base" path as specified in the question though, will it? (Not that it's very clear what is wanted here in the first place.) – Pekka Mar 05 '12 at 08:56
  • it gives http://localhost/test/test_controller/test I only want to get /test or http://localhost/test/ – Milina Udara Mar 05 '12 at 08:57
  • @Milina you need to define more clearly what exactly you want. – Pekka Mar 05 '12 at 08:58
6

You can also use this custom method :

// it will return base domain name only. e.g. yahoo.co.in
function GetBaseUrl() {
    try {
        var url = location.href;

        var start = url.indexOf('//');
        if (start < 0)
            start = 0 
        else 
            start = start + 2;

        var end = url.indexOf('/', start);
        if (end < 0) end = url.length - start;

        var baseURL = url.substring(start, end);
        return baseURL;
    }
    catch (arg) {
        return null;
    }
}
Samuel Caillerie
  • 8,259
  • 1
  • 27
  • 33
Nitesh Kumar
  • 91
  • 1
  • 4
0

If you're getting the current page's url, check out the link object.

You'll probably want document.hostname or document.host.

If your looking for the hostname of a link inside the document, see this conversation

Community
  • 1
  • 1
David Hobs
  • 4,351
  • 2
  • 21
  • 22