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( "https://stackoverflow.com/" );
var protocol = pathArray[0];
var host = pathArray[2];
var url = protocol + '//' + host;

Or use Davids solution from below.

Leave a Comment