最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - base url using jQuery - Stack Overflow

programmeradmin1浏览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/

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
Add a comment  | 

3 Answers 3

Reset to default 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];

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

发布评论

评论列表(0)

  1. 暂无评论