To get the origin of any url, including paths within a website (/my/path
) or schemaless (//example.com/my/path
), or full (http://example.com/my/path
) I put together a quick function.
In the snippet below, all three calls should log https://stacksnippets.net
.
function getOrigin(url)_x000D_
{_x000D_
if(/^\/\//.test(url))_x000D_
{ // no scheme, use current scheme, extract domain_x000D_
url = window.location.protocol + url;_x000D_
}_x000D_
else if(/^\//.test(url))_x000D_
{ // just path, use whole origin_x000D_
url = window.location.origin + url;_x000D_
}_x000D_
return url.match(/^([^/]+\/\/[^/]+)/)[0];_x000D_
}_x000D_
_x000D_
console.log(getOrigin('https://stacksnippets.net/my/path'));_x000D_
console.log(getOrigin('//stacksnippets.net/my/path'));_x000D_
console.log(getOrigin('/my/path'));
_x000D_