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/
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? Commented Mar 5, 2012 at 8:57
  • 1
    possible duplicate of Find base name in URL in Javascript Commented Mar 5, 2012 at 8:57

3 Answers 3

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];
Sign up to request clarification or add additional context in comments.

3 Comments

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.)
it gives localhost/test/test_controller/test I only want to get /test or localhost/test
@Milina you need to define more clearly what exactly you want.
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;
    }
}

Comments

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

1 Comment

dead link. please fix or delete

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.