How to extract base URL from a string in JavaScript?
Edit: Some complain that it doesn't take into account protocol. So I decided to upgrade the code, since it is marked as answer. For those who like one-line-code... well sorry this why we use code minimizers, code should be human readable and this way is better... in my opinion.
var pathArray = "https://somedomain.com".split( '/' );
var protocol = pathArray[0];
var host = pathArray[2];
var url = protocol + '//' + host;
Or use Davids solution from below.
WebKit-based browsers, Firefox as of version 21 and current versions of Internet Explorer (IE 10 and 11) implement location.origin
.
location.origin
includes the protocol, the domain and optionally the port of the URL.
For example, location.origin
of the URL http://www.sitename.com/article/2009/09/14/this-is-an-article/
is http://www.sitename.com
.
To target browsers without support for location.origin
use the following concise polyfill:
if (typeof location.origin === 'undefined')
location.origin = location.protocol + '//' + location.host;
Don't need to use jQuery, just use
location.hostname