5 points

How to Get the Domain From A URL Using Javascript


dashboard

Fri Jan 10 2020 22:36:50 GMT+0000 (UTC)

Posted by @saint_r0ses #javascript #promises #howto

var url = "http://scratch99.com/web-development/javascript/";
var urlParts = url.replace('http://','').replace('https://','').split(/[/?#]/);
var domain = urlParts[0];
content_copy Copy

line 2: "First, the .replace('http://','') strips the http:// off the URL. I do this for the reasons explained above, but it also makes the rest of the code simpler. If we don’t do this, then depending on whether the http:// is present or not, the domain name may be either the 1st or 3rd element of the split result array. If we strip it, it will always be the first element. Next, the .split(/[/?#]/) splits the resulting string based on regex. The string will be split into parts, based not just on the forward slash, but also on the ? and # characters. The first item of the resulting array will be the hostname. This works, but I’m far from a regex master, so if any has a better way of doing this, let me know in the comments." line 3: "Finally, the [0] gets the first element of the array resulting from the split method. "

http://scratch99.com/web-development/javascript/how-to-get-the-domain-from-a-url/