Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get base url with jquery or javascript?

People also ask

How do I find the base URL?

To find the base URL of your website, go to the site's front page. What you see in the address bar on your site's front page is the base URL of your website.

How do I find the base URL in HTML?

The <base> tag specifies the base URL and/or target for all relative URLs in a document. The <base> tag must have either an href or a target attribute present, or both. There can only be one single <base> element in a document, and it must be inside the <head> element.

How do I get the URL of a website using JavaScript?

You can simply call the window. location. href property which will return you the complete URL of the webpage including hostname, pathname, and query string. Let's test the JavaScript property practically.

Which method returns the base URL for the object?

Returns the base URL for the object.


This one will help you...

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

I think this will work well for you:

var base_url = window.location.origin;

var host = window.location.host;

var pathArray = window.location.pathname.split( '/' );

This will get base url

var baseurl = window.location.origin+window.location.pathname;

This is an extremely old question, but here are the approaches I personally use ...

Get Standard/Base URL

As many have already stated, this works for most situations.

var url = window.location.origin;


Get Absolute Base URL

However, this simple approach can be used to strip off any port numbers.

var url = "http://" + location.host.split(":")[0];

Edit: To address the concern, posed by Jason Rice, the following can be used to automatically insert the correct protocol type ...

var url = window.location.protocol + "//" + location.host.split(":")[0];


Set Base URL

As a bonus -- the base URL can then be redefined globally.

document.head.innerHTML = document.head.innerHTML + "<base href='" + url + "' />";