Get protocol, domain, and port from URL
const full = location.protocol + '//' + location.host;
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' }