1

I am trying to get the site base url using javascript . I am using

var pathArray = window.location.pathname.split( '/' );
var baseURL = window.location.protocol + "//" + window.location.host + "/" + pathArray[1]+'/';

This is working for mysite.com/project1 but not for mysite.com.

How can I check this for both the urls ? I have to send ajax request to the url.

Thanks in advance.

2
  • Please remove the PHP tag, this question has fundamentally nothing to do with PHP. Commented Nov 24, 2014 at 8:51
  • possible duplicate of Get current URL in JavaScript? Commented Nov 24, 2014 at 8:59

4 Answers 4

1

This one should work (depending on your definition of "base URL"):

<script>
 /**
 * Get the parts of an URL.
 *
 * @param url URL to fetch information from
 * @return parts of an URL
 */
function getURLParts(url) {
    var parser = document.createElement('a');
    parser.href = url;
    return parser;
}

// Show the URL information
var parser = getBaseURL(window.location);
alert(parser.protocol);
alert(parser.host);
alert(parser.hostname);
alert(parser.port);
alert(parser.pathname);
alert(parser.hash);
alert(parser.search);
</script>

Sign up to request clarification or add additional context in comments.

Comments

0

Base URL should be defined in a special tag in header:

<head>
<base href="http://example.com/project1/">
</head>

Then you can read it with Javascript: in modern browsers

var baseURL = document.baseURI

or in older

var baseURL = document.getElementsByTagName('base')[0].href

Comments

0

simply use the location property of window e.g. window.location.href

<script>
  alert(window.location.href);
</script>

Comments

0

I guess you need the base URL of the current Website. From this answer:

pathArray = window.location.href.split( '/' );
protocol = pathArray[0];
host = pathArray[2];
url = protocol + '//' + host;

Comments

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.