Get protocol, domain, and port from URL

JavascriptUrlDnsProtocolsPort

Javascript Problem Overview


I need to extract the full protocol, domain, and port from a given URL. For example:

https://localhost:8181/ContactUs-1.0/contact?lang=it&report_type=consumer
>>>
https://localhost:8181

Javascript Solutions


Solution 1 - Javascript

const full = location.protocol + '//' + location.host;

Solution 2 - Javascript

None of these answers seem to completely address the question, which calls for an arbitrary url, not specifically the url of the current page.

Method 1: Use the URL API (caveat: no IE11 support)

You can use the URL API (not supported by IE11, but available everywhere else).

This also makes it easy to access search params. Another bonus: it can be used in a Web Worker since it doesn't depend on the DOM.

const url = new URL('http://example.com:12345/blog/foo/bar?startIndex=1&pageSize=10');
Method 2 (old way): Use the browser's built-in parser in the DOM

Use this if you need this to work on older browsers as well.

//  Create an anchor element (note: no need to append this element to the document)
const url = document.createElement('a');
//  Set href to any path
url.setAttribute('href', 'http://example.com:12345/blog/foo/bar?startIndex=1&pageSize=10');
That's it!

The browser's built-in parser has already done its job. Now you can just grab the parts you need (note that this works for both methods above):

//  Get any piece of the url you're interested in
url.hostname;  //  'example.com'
url.port;      //  12345
url.search;    //  '?startIndex=1&pageSize=10'
url.pathname;  //  '/blog/foo/bar'
url.protocol;  //  'http:'
Bonus: Search params

Chances are you'll probably want to break apart the search url params as well, since '?startIndex=1&pageSize=10' isn't too useable on its own.

If you used Method 1 (URL API) above, you simply use the searchParams getters:

url.searchParams.get('startIndex');  // '1'

Or to get all parameters:

function searchParamsToObj(searchParams) {
  const paramsMap = Array
    .from(url.searchParams)
    .reduce((params, [key, val]) => params.set(key, val), new Map());
  return Object.fromEntries(paramsMap);
}
searchParamsToObj(url.searchParams);
// -> { startIndex: '1', pageSize: '10' }

If you used Method 2 (the old way), you can use something like this:

// Simple object output (note: does NOT preserve duplicate keys).
var params = url.search.substr(1); // remove '?' prefix
params
	.split('&')
	.reduce((accum, keyval) => {
		const [key, val] = keyval.split('=');
		accum[key] = val;
		return accum;
	}, {});
// -> { startIndex: '1', pageSize: '10' }

Solution 3 - Javascript

first get the current address

var url = window.location.href

Then just parse that string

var arr = url.split("/");

your url is:

var result = arr[0] + "//" + arr[2]

Hope this helps

Solution 4 - Javascript

For some reason all the answers are all overkills. This is all it takes:

window.location.origin

More details can be found here: https://developer.mozilla.org/en-US/docs/Web/API/window.location#Properties

Solution 5 - Javascript

As has already been mentioned there is the as yet not fully supported window.location.origin but instead of either using it or creating a new variable to use, I prefer to check for it and if it isn't set to set it.

For example;

if (!window.location.origin) {
  window.location.origin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port: '');
}

I actually wrote about this a few months back A fix for window.location.origin

Solution 6 - Javascript

host

var url = window.location.host;

returns localhost:2679

hostname

var url = window.location.hostname;

returns localhost

Solution 7 - Javascript

window.location.origin will be enough to get the same.

Solution 8 - Javascript

Why not use:

let full = window.location.origin

Solution 9 - Javascript

> The protocol property sets or returns the protocol of the current URL, including the colon (:).

This means that if you want to get only the HTTP/HTTPS part you can do something like this:

var protocol = window.location.protocol.replace(/:/g,'')

For the domain you can use:

var domain = window.location.hostname;

For the port you can use:

var port = window.location.port;

Keep in mind that the port will be an empty string if it is not visible in the URL. For example:

If you need to show 80/443 when you have no port use

var port = window.location.port || (protocol === 'https' ? '443' : '80');

Solution 10 - Javascript

Indeed, window.location.origin works fine in browsers following standards, but guess what. IE isn't following standards.

So because of that, this is what worked for me in IE, FireFox and Chrome:

var full = location.protocol+'//'+location.hostname+(location.port ? ':'+location.port: '');

but for possible future enhancements which could cause conflicts, I specified the "window" reference before the "location" object.

var full = window.location.protocol+'//'+window.location.hostname+(window.location.port ? ':'+window.location.port: '');

Solution 11 - Javascript

Here is the solution I'm using:

const result = `${ window.location.protocol }//${ window.location.host }`;

EDIT:

To add cross-browser compatibility, use the following:

const result = `${ window.location.protocol }//${ window.location.hostname + (window.location.port ? ':' + window.location.port: '') }`;

Solution 12 - Javascript

var http = location.protocol;
var slashes = http.concat("//");
var host = slashes.concat(window.location.hostname);

Solution 13 - Javascript

var getBasePath = function(url) {
    var r = ('' + url).match(/^(https?:)?\/\/[^/]+/i);
    return r ? r[0] : '';
};

Solution 14 - Javascript

Try use a regular expression (Regex), which will be quite useful when you want to validate / extract stuff or even do some simple parsing in javascript.

The regex is :

/([a-zA-Z]+):\/\/([\-\w\.]+)(?:\:(\d{0,5}))?/

Demonstration:

function breakURL(url){

     matches = /([a-zA-Z]+):\/\/([\-\w\.]+)(?:\:(\d{0,5}))?/.exec(url);

     foo = new Array();

     if(matches){
          for( i = 1; i < matches.length ; i++){ foo.push(matches[i]); }
     }

     return foo
}

url = "https://www.google.co.uk:55699/search?q=http%3A%2F%2F&oq=http%3A%2F%2F&aqs=chrome..69i57j69i60l3j69i65l2.2342j0j4&sourceid=chrome&ie=UTF-8"


breakURL(url);       // [https, www.google.co.uk, 55699] 
breakURL();          // []
breakURL("asf");     // []
breakURL("asd://");  // []
breakURL("asd://a"); // [asd, a, undefined]

Now you can do validation as well.

Solution 15 - Javascript

With ES6 template literals:

const url = `${location.protocol}//${location.hostname}${location.port?':'+location.port:''}`;

document.getElementById("result").innerText = url;

<div id="result"></div>

And you can simplify to:

const url = `${location.protocol}//${location.host}`;

document.getElementById("result").innerText = url;

<div id="result"></div>

Solution 16 - Javascript

Simple answer that works for all browsers:

let origin;

if (!window.location.origin) {
  origin = window.location.protocol + "//" + window.location.hostname + 
     (window.location.port ? ':' + window.location.port: '');
}

origin = window.location.origin;


Solution 17 - Javascript

ES6 style with configurable parameters.

/**
 * Get the current URL from `window` context object.
 * Will return the fully qualified URL if neccessary:
 *   getCurrentBaseURL(true, false) // `http://localhost/` - `https://localhost:3000/`
 *   getCurrentBaseURL(true, true) // `http://www.example.com` - `https://www.example.com:8080`
 *   getCurrentBaseURL(false, true) // `www.example.com` - `localhost:3000`
 *
 * @param {boolean} [includeProtocol=true]
 * @param {boolean} [removeTrailingSlash=false]
 * @returns {string} The current base URL.
 */
export const getCurrentBaseURL = (includeProtocol = true, removeTrailingSlash = false) => {
  if (!window || !window.location || !window.location.hostname || !window.location.protocol) {
    console.error(
      `The getCurrentBaseURL function must be called from a context in which window object exists. Yet, window is ${window}`,
      [window, window.location, window.location.hostname, window.location.protocol],
    )
    throw new TypeError('Whole or part of window is not defined.')
  }

  const URL = `${includeProtocol ? `${window.location.protocol}//` : ''}${window.location.hostname}${
    window.location.port ? `:${window.location.port}` : ''
  }${removeTrailingSlash ? '' : '/'}`

  // console.log(`The URL is ${URL}`)

  return URL
}

Solution 18 - Javascript

window.location.protocol + '//' + window.location.host

Solution 19 - Javascript

console.log(`${req.protocol}://${req.get('host')}/${req.originalUrl}`);
  • req.protocol - gives the protocol you used (e.g. HTTP)
  • req.get(host) - gives the host name with the port number (e.g. localhost:8080)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionyelo3View Question on Stackoverflow
Solution 1 - JavascriptShefView Answer on Stackoverflow
Solution 2 - JavascriptDavid CalhounView Answer on Stackoverflow
Solution 3 - JavascriptwezzyView Answer on Stackoverflow
Solution 4 - JavascriptPijusnView Answer on Stackoverflow
Solution 5 - JavascriptTobyView Answer on Stackoverflow
Solution 6 - JavascriptMiroslav HolecView Answer on Stackoverflow
Solution 7 - Javascriptint soumenView Answer on Stackoverflow
Solution 8 - JavascriptMaik de KruifView Answer on Stackoverflow
Solution 9 - JavascriptДамян СтанчевView Answer on Stackoverflow
Solution 10 - JavascriptcpuView Answer on Stackoverflow
Solution 11 - JavascriptJulienRiouxView Answer on Stackoverflow
Solution 12 - JavascriptElankeeranView Answer on Stackoverflow
Solution 13 - JavascripthaipengView Answer on Stackoverflow
Solution 14 - Javascripted9w2in6View Answer on Stackoverflow
Solution 15 - JavascriptCraigoView Answer on Stackoverflow
Solution 16 - JavascriptMike HawesView Answer on Stackoverflow
Solution 17 - JavascriptSébastienView Answer on Stackoverflow
Solution 18 - JavascriptCode_WormView Answer on Stackoverflow
Solution 19 - JavascriptPrabhat RoyView Answer on Stackoverflow