There might be times when you really want to get the URL of the site collection within the master page of sharepoint 2013 sites.
well you can achieve it by using the below javascript line .
Inorder to add script in masterpage , we have to follow the conventional and well known method of the script tag inside the body of HTML.
now within the script tag just copy paste the following function
function getSiteCollectionsURL()
{
var sitecollectionURL = window.location.protocol + "//" + window.location.host +_spPageContextInfo.siteServerRelativeUrl
return sitecollectionURL;
}the function can be called from anywhere inside the masterpage according to your needs.. it will return the site collection url no matter where you are , ie , whether you are in the subsite or the site collection or the nested subsite.