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/
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/
Share
Improve this question
edited Mar 5, 2012 at 13:04
user647772
asked Mar 5, 2012 at 8:53
Milina UdaraMilina Udara
5971 gold badge9 silver badges24 bronze badges
2
- 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 Commented Mar 5, 2012 at 8:57
- 1 possible duplicate of Find base name in URL in Javascript – Yi Jiang Commented Mar 5, 2012 at 8:57
3 Answers
Reset to default 9You 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];
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;
}
}
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