Get hostname (base url) using javascript

I am getting too many ways to get the hostname like below:

window.location.host // you'll get sub.domain.com:8080 or sub.domain.com:80
window.location.hostname // you'll get sub.domain.com
window.location.protocol // you'll get http:
window.location.port // you'll get 8080 or 80
window.location.pathname // you'll get /virtualPath

      

In my case, I want something different. For example:

My site name QA example.com/testsite/index.html

Name of my PROD site example.com/index.html

The problem using the above methods to get the hostname only returns me the hostname like this: example.com

However, for QA I need to return example.com/testsite

For PROD I need to return example.com

Is this possible with one code? Thanks in advance.

+3


source to share


3 answers


To achieve the required you need to check window.location.hostname

as well as the first folder in window.location.pathname

. Something like that:



function getPath() {
  var folder = (window.location.pathname.split('/')[0] || '').toLowerCase() == 'testsite' ? '/testsite' : '';
  return window.location.hostname + folder;
}

      

+3


source


The best method that works for both PROD and QA



var BASE_URL = window.location.href;
    BASE_URL = BASE_URL.split("testsite");
    if (BASE_URL.length > 1)
    {
        BASE_URL = BASE_URL[0];
        BASE_URL = BASE_URL + 'testsite';
    } else{
        BASE_URL = window.location.origin;
   }

      

+1


source


Use window.location.hostname;

Example: Page
URL http: // localhost: 2239 / Default2.aspx? Id = 5 & name = SatinderSingh

var getCurrentURL =window.location.href; //http://localhost:2239/Default2.aspx?id=5&name=SatinderSingh
var getHostname=window.location.hostname; //localhost
var getPathName=window.location.pathname  // Default2.aspx
var getPortNo=window.location.port        // 2239
var getQueryString=window.location.search //?id=5&name=SatinderSingh

      


   var getHostname = window.location.hostname; //localhost
   var getPathName = window.location.pathname  // Default2.aspx
   var split_PathName = String(getPathName.split("/"));        
   var FinalURL = getHostname + "/" + split_PathName[1]

      

0


source







All Articles