How to Extract the Hostname Portion of a Url in JavaScript

How to extract the hostname portion of a URL in JavaScript

suppose that you have a page with this address: http://sub.domain.com/virtualPath/page.htm. use the following in page code to achieve those results:

  • 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
  • window.location.origin : you'll get http://sub.domain.com *****

Update: about the .origin

***** As the ref states, browser compatibility for window.location.origin is not clear. I've checked it in chrome and it returned http://sub.domain.com:port if the port is anything but 80, and http://sub.domain.com if the port is 80.

Special thanks to @torazaburo for mentioning that to me.

Extract hostname name from string

There is no need to parse the string, just pass your URL as an argument to URL constructor:

const url = 'http://www.youtube.com/watch?v=ClkQA2Lb_iE';
const { hostname } = new URL(url);

console.assert(hostname === 'www.youtube.com');

How do I parse a URL into hostname and path in javascript?

var getLocation = function(href) {
var l = document.createElement("a");
l.href = href;
return l;
};
var l = getLocation("http://example.com/path");
console.debug(l.hostname)
>> "example.com"
console.debug(l.pathname)
>> "/path"

how to Extract hostname from url using jquery

To do that you can simply use the String.prototype.split() method with / as delimiter to extract the hostname and then you take the end of the hostname (that contains a dot) with String.prototype.match():

var m = url.split('/')[0].match(/[^.]+\.[^.]+$/);
if (m)
var domain = m[0];

Note: if the url begins with a scheme you need to remove it before:

var pat = '^https?://';
url = url.replace(new RegExp(pat, 'i'), '');

An other way consists to find the domain directly:

var pat = '^(?:https?://)?(?:[^/:]*:[^/@]*@)?[^/]*([^./]+\\.[^./]+)';
var m = url.match(new RegExp(pat, 'i'));
if (m)
var domain = m[1];

But in this case, you need to deal with a possible login/pass part before the hostname. This is the reason of this subpattern: (?:[^/:]*:[^/@]*@)?

How to get the host URL using JavaScript from the current page

// will return the host name and port
var host = window.location.host;

or possibly

var host = window.location.protocol + "//" + window.location.host;

or if you like concatenation

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

// or as you probably should do
var host = location.protocol.concat("//").concat(window.location.host);

// the above is the same as origin, e.g. "https://stackoverflow.com"
var host = window.location.origin;

If you have or expect custom ports use window.location.host instead of window.location.hostname

How to get the last portion from the url using javascript ?

var curPage = window.location.pathname;

See this URL for more info

How to extract the hostname portion of a URL in JavaScript

Get protocol, domain, and port from URL

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

How to extract base URL from a string in JavaScript?

Edit: Some complain that it doesn't take into account protocol. So I decided to upgrade the code, since it is marked as answer. For those who like one-line-code... well sorry this why we use code minimizers, code should be human readable and this way is better... in my opinion.

var pathArray = "https://somedomain.com".split( '/' );
var protocol = pathArray[0];
var host = pathArray[2];
var url = protocol + '//' + host;

Or use Davids solution from below.

Trying to extract the URL hostname from API response

Try not creating new URL instance after useEffect. It will not update immediately.
Kindly read this (https://stackoverflow.com/a/58877875/11646865)

const Articles = props => {

const [article, setArticle] = useState([]);
const [url, setUrl] = useState([]);

useEffect(() =>{
axios.get(`https://example.com/item/${props.source}.json`)
.then((response)=>{
console.log(response)
setUrl(new URL(response.data.url))
setArticle(response.data)
})
}, [props.source])

return(

<div>
<h1>{article.title}</h1>
<a href={article.url}>
<p>{url.hostname}</p>
</a>
</div>

)}

export default Articles


Related Topics



Leave a reply



Submit