Get the domain name of the subdomain Javascript - javascript

How i can get the domain name example.com from the set of possible subdomains sub1.example.com sub2.example.com sub3.example.com using javascript ...?

var parts = location.hostname.split('.');
var subdomain = parts.shift();
var upperleveldomain = parts.join('.');
To get only the second-level-domain, you might use
var parts = location.hostname.split('.');
var sndleveldomain = parts.slice(-2).join('.');

The accepted answer will work to get the second level domain. However, there is something called "public suffixes" that you may want to take into account. Otherwise, you may get unexpected and erroneous results.
For example, take the domain www.amazon.co.uk.
If you just try getting the second level domain, you'll end up with co.uk, which is probably not what you want. That's because co.uk is a "public suffix", which means it's essentially a top level domain. Here's the definition of a public suffix, taken from https://publicsuffix.org:
A "public suffix" is one under which Internet users can (or historically could) directly register names.
If this is a crucial part of your application, I would look into something like psl (https://github.com/lupomontero/psl) for domain parsing. It works in nodejs and the browser, and it's tested on Mozilla's maintained public suffix list.
Here's a quick example from their README:
var psl = require('psl');
// TLD with some 2-level rules.
psl.get('uk.com'); // null);
psl.get('example.uk.com'); // 'example.uk.com');
psl.get('b.example.uk.com'); // 'example.uk.com');

This is faster
const firstDotIndex = subDomain.indexOf('.');
const domain = subDomain.substring(firstDotIndex + 1);

The generic solution is explained here http://rossscrivener.co.uk/blog/javascript-get-domain-exclude-subdomain
From above link
var domain = (function(){
var i=0,domain=document.domain,p=domain.split('.'),s='_gd'+(new Date()).getTime();
while(i<(p.length-1) && document.cookie.indexOf(s+'='+s)==-1){
domain = p.slice(-1-(++i)).join('.');
document.cookie = s+"="+s+";domain="+domain+";";
}
document.cookie = s+"=;expires=Thu, 01 Jan 1970 00:00:01 GMT;domain="+domain+";";
return domain;
})();

function getDomain() {
const hostnameArray = window.location.hostname.split('.')
const numberOfSubdomains = hostnameArray.length - 2
return hostnameArray.length === 2 ? window.location.hostname : hostnameArray.slice(numberOfSubdomains).join('.')
}
console.log(getDomain());
This will remove all subdomains, so "a.b.c.d.test.com" will become "test.com"

If you want to verify if a specific subdomain exists
var parts = location.hostname.split('.');
if(parts.includes('subdomain_to_search_here')){
//yes
}else{
//no
}

some more robust version, which is independent of the subdomain count
function getDomain() {
const hostname = window.location.hostname.split('.');
hostname.reverse();
return `${hostname[1]}.${hostname[0]}`;
}

Related

How to get domain from email address in Javascript?

I want to get the domain part from an email address, in Javascript. It's easy to extract the domain from an email like via split: "joe#example.com", which is example.com.
However, emails also come in forms like "joe#subdomain1.example.com.uk", of which the domain is example.com.uk, instead of subdomain1.example.com.uk. The problem here is that subdomain1 can be mistakenly considered as part of the domain.
How do I do this reliably?
That is really not a trivial problem as it might seem at first glance.
Luckily there are libs that solves this, tld-extract is a popular choice which uses Mozilla's Public Suffix List (a volunteer based list). The usage is
var parser = require('tld-extract');
console.log( parser("www.google.com") );
console.log( parser("google.co.uk") );
/**
* >> { tld: 'com', domain: 'google.com', sub: 'www' }
* >> { tld: 'co.uk', domain: 'google.co.uk', sub: '' }
*/
To extract the server address part from email address first split by # character like this
const email = "john#sub.domain.com"
const address = email.split('#').pop()
const domain = parser(address).domain
See more in depth discussion about the problem solution check the README of a similar python library.
tldextract on the other hand knows what all gTLDs and ccTLDs look like
by looking up the currently living ones according to the Public Suffix
List (PSL). So, given a URL, it knows its subdomain from its domain,
and its domain from its country code.
Make sure to learn about the list on Public Suffix List website and understand it is based on volunteer work and might not be exhaustive at all time.
The Public Suffix List is a cross-vendor initiative to provide an
accurate list of domain name suffixes, maintained by the hard work of
Mozilla volunteers and by submissions from registries, to whom we are
very grateful.
Since there was and remains no algorithmic method of finding the
highest level at which a domain may be registered for a particular
top-level domain (the policies differ with each registry), the only
method is to create a list. This is the aim of the Public Suffix List.
I agree that the best solution for this problem would be to use a library, like what was suggested in https://stackoverflow.com/a/49893282/2735286.
Yet if you have a long enough list with top level domains and subdomains, you could write some code which extracts whatever characters are found after the '#' sign and then from the domain you try to find out whether you have a top level or subdomain. When you know if you are dealing with a top level domain you know where you can find the main domain name and so everything before it must be a subdomain. The same applies to the subdomain.
This is a naive implementation, but you could try this:
// TODO: needs to have an exhaustive list of top level domains
const topLevelDomains = ["com", "org", "int", "gov", "edu", "net", "mil"];
// TODO: Needs an exhaustive list of subdomains
const subdomains = ["co.uk", "org.uk", "me.uk", "ltd.uk", "plc.uk"];
function extract(str) {
const suffix = str.match(/.+#(.+)/);
if (suffix) {
const groups = suffix.pop().split(".");
const lastPart = groups[groups.length - 1];
if (isSubDomain(groups[groups.length - 2] + "." + lastPart)) {
console.log("Sub domain detected in: " + groups);
if (groups.length > 3) {
console.log("Possible subdomain: " + groups.splice(0, groups.length - 3));
console.log();
}
} else if (isTopLevelDomain(lastPart)) {
console.log("Top level domain detected in: " + groups);
if (groups.length > 2) {
console.log("Possible subdomain: " + groups.splice(0, groups.length - 2));
console.log();
}
}
}
}
function isTopLevelDomain(lastPart) {
return (topLevelDomains.find(s => s === lastPart));
}
function isSubDomain(lastPart) {
return (subdomains.find(s => s === lastPart));
}
extract("joe#example.com");
extract("joe#subdomain1.example.co.uk");
extract("joe#subdomain2.example.edu");
extract("joe#subdomain3.example.ltd.uk");
extract("joe#test.subdomain3.example.plc.uk");
Please challenge the logic, if I got this wrong.
// Not a proper solution because of email pattern is not fixed. Use below if it is appropriate solution according to your problem .
jQuery( document ).ready(function() {
//var input = 'joe#subdomain1.com';
var input = 'joe#subdomain1.example.com.uk';
var first_split = input.split("#")[1];
var second_split = first_split.split(".");
if(second_split.length == 2) {
console.log('domain is : '+first_split);
} else if(second_split.length > 2) {
var str = first_split.substring(first_split.indexOf(".") + 1);
console.log('domain is : '+str);
}
});

JavaScript Regex URL extract domain only

Currently I can extract the 'domain' from any URL with the following regex:
/^(?:https?:\/\/)?(?:[^#\n]+#)?(?:www\.)?([^:\/\n\?\=]+)/im
However I'm also getting subdomain's too which I want to avoid. For example if I have sites:
www.google.com
yahoo.com/something
freds.meatmarket.co.uk?someparameter
josh.meatmarket.co.uk/asldf/asdf
I currently get:
google.com
yahoo.com
freds.meatmarket.co.uk
josh.meatmarket.co.uk
Those last two I would like to exclude the freds and josh subdomain portion and extract only the true domain which would just be meatmarket.co.uk.
I did find another SOF that tries to solve in PHP, unfortunately I don't know PHP. is this translatable to JS (I'm actually using Google Script FYI)?
function topDomainFromURL($url) {
$url_parts = parse_url($url);
$domain_parts = explode('.', $url_parts['host']);
if (strlen(end($domain_parts)) == 2 ) {
// ccTLD here, get last three parts
$top_domain_parts = array_slice($domain_parts, -3);
} else {
$top_domain_parts = array_slice($domain_parts, -2);
}
$top_domain = implode('.', $top_domain_parts);
return $top_domain;
}
So, you need firstmost hostname stripped from your result, unless there only two parts already?
Just postprocess your result from first match with regexp matching that condition:
function domain_from_url(url) {
var result
var match
if (match = url.match(/^(?:https?:\/\/)?(?:[^#\n]+#)?(?:www\.)?([^:\/\n\?\=]+)/im)) {
result = match[1]
if (match = result.match(/^[^\.]+\.(.+\..+)$/)) {
result = match[1]
}
}
return result
}
console.log(domain_from_url("www.google.com"))
console.log(domain_from_url("yahoo.com/something"))
console.log(domain_from_url("freds.meatmarket.co.uk?someparameter"))
console.log(domain_from_url("josh.meatmarket.co.uk/asldf/asdf"))
// google.com
// yahoo.com
// meatmarket.co.uk
// meatmarket.co.uk
Try this:
https?:\/\/(www\.)?[-a-zA-Z0-9#:%._\+~#=]{2,256}\.([a-z]{2,6}){1}
Try to replace www by something else:
/^(?:https?:\/\/)?(?:[^#\n]+#)?(?:[^.]+\.)?([^:\/\n\?\=]+)/im
EDIT:
If you absolutely want to preserve the www into your regex, you could try this one:
/^(?:https?:\/\/)?(?:[^#\n]+#)?(?:www\.)?(?:[^.]+\.)?([^:\/\n\?\=]+)/im
export const extractHostname = url => {
let hostname;
// find & remove protocol (http, ftp, etc.) and get hostname
if (url.indexOf("://") > -1)
{
hostname = url.split('/')[2];
}
else
{
hostname = url.split('/')[0];
}
// find & remove port number
hostname = hostname.split(':')[0];
// find & remove "?"
hostname = hostname.split('?')[0];
return hostname;
};
export const extractRootDomain = url => {
let domain = extractHostname(url),
splitArr = domain.split('.'),
arrLen = splitArr.length;
// extracting the root domain here
// if there is a subdomain
if (arrLen > 2)
{
domain = splitArr[arrLen - 2] + '.' + splitArr[arrLen - 1];
// check to see if it's using a Country Code Top Level Domain (ccTLD) (i.e. ".me.uk")
if (splitArr[arrLen - 2].length === 2 && splitArr[arrLen - 1].length === 2)
{
//this is using a ccTLD
domain = splitArr[arrLen - 3] + '.' + domain;
}
}
return domain;
};
This is what I've come up with. I don't know how to combine the two match rules into a single regexp, however. This routine won't properly process bad domains like example..com. It does, however, account for TLDs that are in the variety of .xx, .xx.xx, .xxx, or more than 4 character TLDs on the end. This routine will work on just domain names or entire URLs, and the URLs don't have to have the http or https protocol -- it could be ftp, chrome, and others.
function getRootDomain(s){
var sResult = ''
try {
sResult = s.match(/^(?:.*\:\/?\/)?(?<domain>[\w\-\.]*)/i).groups.domain
.match(/(?<root>[\w\-]*(\.\w{3,}|\.\w{2}|\.\w{2}\.\w{2}))$/).groups.root;
} catch(ignore) {}
return sResult;
}
So basically, the first routine strips out any potential stuff before the ://, if that exists, or just a :, if that exists. Next, it looks for all non-word boundary stuff except allows the dash and period like you'd potentially see in domains. It labels this into a named capture group called domain. It also prevents the domain match from including a port such as :8080 as an example. If given an empty string, it just returns an empty string back.
From there, we then do another pass on this and instead of looking from the left-to-right like you would with the preceding ^ symbol, we use the ending $ symbol, working right-to-left, and allow only 4 conditions on the end: .xx.xx, .xx, .xxx, or more than .xxx (such as 4+ character TLDs), where x is a non-word boundary item. Note the {3,} -- that means 3 or more of something, which is why we handle the TLDs that are 3 or more characters too. From there, we allow for a non-word boundary in front of that which may include dashes and periods.
EDIT: Since posting this answer, I learned how to combine the full domain and the root part into one single RegExp. However, I'll keep the above for reasons where you may want to get both values, although the function only returned the root (but with a quick edit, could have returned both full domain and root domain). So, if you just want the root alone, then you could use this solution:
function getRootDomain(s){
var sResult = ''
try {
sResult = s.match(/^(?:.*?:\/\/)?.*?(?<root>[\w\-]*(?:\.\w{2,}|\.\w{2}\.\w{2}))(?:[\/?#:]|$)/).groups.root;
} catch(ignore) {}
return sResult;
}

Remove empty querystring [duplicate]

What is an easy way to remove the querystring from a Path in Javascript?
I have seen a plugin for Jquery that uses window.location.search. I can not do that: The URL in my case is a variable that is set from AJAX.
var testURL = '/Products/List?SortDirection=dsc&Sort=price&Page=3&Page2=3&SortOrder=dsc'
An easy way to get this is:
function getPathFromUrl(url) {
return url.split("?")[0];
}
For those who also wish to remove the hash (not part of the original question) when no querystring exists, that requires a little bit more:
function stripQueryStringAndHashFromPath(url) {
return url.split("?")[0].split("#")[0];
}
EDIT
#caub (originally #crl) suggested a simpler combo that works for both query string and hash (though it uses RegExp, in case anyone has a problem with that):
function getPathFromUrl(url) {
return url.split(/[?#]/)[0];
}
2nd Update: In attempt to provide a comprehensive answer, I am benchmarking the three methods proposed in the various answers.
var testURL = '/Products/List?SortDirection=dsc&Sort=price&Page=3&Page2=3';
var i;
// Testing the substring method
i = 0;
console.time('10k substring');
while (i < 10000) {
testURL.substring(0, testURL.indexOf('?'));
i++;
}
console.timeEnd('10k substring');
// Testing the split method
i = 0;
console.time('10k split');
while (i < 10000) {
testURL.split('?')[0];
i++;
}
console.timeEnd('10k split');
// Testing the RegEx method
i = 0;
var re = new RegExp("[^?]+");
console.time('10k regex');
while (i < 10000) {
testURL.match(re)[0];
i++;
}
console.timeEnd('10k regex');
Results in Firefox 3.5.8 on Mac OS X 10.6.2:
10k substring: 16ms
10k split: 25ms
10k regex: 44ms
Results in Chrome 5.0.307.11 on Mac OS X 10.6.2:
10k substring: 14ms
10k split: 20ms
10k regex: 15ms
Note that the substring method is inferior in functionality as it returns a blank string if the URL does not contain a querystring. The other two methods would return the full URL, as expected. However it is interesting to note that the substring method is the fastest, especially in Firefox.
1st UPDATE: Actually the split() method suggested by Robusto is a better solution that the one I suggested earlier, since it will work even when there is no querystring:
var testURL = '/Products/List?SortDirection=dsc&Sort=price&Page=3&Page2=3';
testURL.split('?')[0]; // Returns: "/Products/List"
var testURL2 = '/Products/List';
testURL2.split('?')[0]; // Returns: "/Products/List"
Original Answer:
var testURL = '/Products/List?SortDirection=dsc&Sort=price&Page=3&Page2=3';
testURL.substring(0, testURL.indexOf('?')); // Returns: "/Products/List"
This may be an old question but I have tried this method to remove query params. Seems to work smoothly for me as I needed a reload as well combined with removing of query params.
window.location.href = window.location.origin + window.location.pathname;
Also since I am using simple string addition operation I am guessing the performance will be good. But Still worth comparing with snippets in this answer
var u = new URL('https://server.de/test?q#h')
u.hash = ''
u.search = ''
console.log(u.toString())
var path = "path/to/myfile.png?foo=bar#hash";
console.log(
path.replace(/(\?.*)|(#.*)/g, "")
);
I can understand how painful things were before, In modern days you can get this super easily like below
let url = new URL('https://example.com?foo=1&bar=2&foo=3');
let params = new URLSearchParams(url.search);
// Delete the foo parameter.
params.delete('foo'); //Query string is now: 'bar=2'
// now join the query param and host
let newUrl = url.origin + '/' + params.toString();
A simple way is you can do as follows
public static String stripQueryStringAndHashFromPath(String uri) {
return uri.replaceAll(("(\\?.*|\\#.*)"), "");
}
An approach using the standard URL:
/**
* #param {string} path - A path starting with "/"
* #return {string}
*/
function getPathname(path) {
return new URL(`http://_${path}`).pathname
}
getPathname('/foo/bar?cat=5') // /foo/bar
If you're into RegEx....
var newURL = testURL.match(new RegExp("[^?]+"))
If using backbone.js (which contains url anchor as route), url query string may appear:
before url anchor:
var url = 'http://example.com?a=1&b=3#routepath/subpath';
after url anchor:
var url = 'http://example.com#routepath/subpath?a=1&b=3';
Solution:
window.location.href.replace(window.location.search, '');
// run as: 'http://example.com#routepath/subpath?a=1&b=3'.replace('?a=1&b=3', '');
If you need to perform complex operation on URL, you can take a look to the jQuery url parser plugin.

jquery to get/set href protocol

I have some relative links on my site that need to enforce https even if the current page is http (so I can't just use //links).
I'm guessing there is a pretty easy way for jQuery to retrieve the href upon click, and then set the page location to match the link that was clicked prepended with the HTTPS protocol?
Thanks in advance!
To get the protocol:
document.location.protocol;
to set the protocol:
document.location.protocol = 'https:';
You need a url joining helper function (the one below is modified from another answer I gave). Complete code, assuming you add class="httpsLink" to the special <a> links:
var urlJoin = function(base, relative)
{
// See if there is already a protocol on this
if (relative.indexOf("://") != -1)
return relative;
// See if this is protocol-relative
if (relative.indexOf("//") == 0)
{
var protocolIndex = base.indexOf("://");
return base.substr(0, protocolIndex+1) + relative;
}
// We need to split the domain and the path for the remaining options
var protocolIndexEnd = base.indexOf("://") + 3;
if (base.indexOf("/", protocolIndexEnd) == -1) // append slash if passed only http://bla.com
base += "/";
var endDomainIndex = base.indexOf("/", protocolIndexEnd);
var domain = base.substr(0, endDomainIndex);
var path = base.substr(endDomainIndex);
if (path.lastIndexOf("/") != path.length-1) // trim off any ending file name
path = path.substr(0, path.lastIndexOf("/")+1);
// See if this is site-absolute
if (relative.indexOf("/") == 0)
{
return domain + relative;
}
// See if this is document-relative with ../
while (relative.indexOf("../") == 0)
{
relative = relative.substr(3);
if (path.length > 1)
{
var secondToLastSlashIndex = path.substr(0, path.length-1).lastIndexOf("/");
path = path.substr(0, secondToLastSlashIndex+1);
}
}
// Finally, slap on whatever ending is left
return domain + path + relative;
};
$('a.httpsLink').click(function(e){
e.preventDefault();
location.href = urlJoin(location.href, $(this).attr('href')).split('http://').join('https://');
});
This will work with any type of links, be they absolute or relative.
If you're getting all of the links on a page (unlikely) you can use a global selector:
$('a').click(function(e) {
location.href = this.attr('href').replace("http://", "https://");
});
If you need to be more selective, you can apply a custom class selector to get only certain ones (this class would then have to be applied to those links):
$('.outsideLinkClass').click(function(e) {
location.href = this.attr('href').replace("http://", "https://");
});
Edit:
After re-reading my answer a little, it occurred to me that the simple replace option might not work if you're using internal links that are based off relative urls. In such a case you will need to make the assignment code a little more involved to ensure that you're modifying a full url and not just trusting to the replace.
Edit 2:
An idea for a more robust protocol replacement:
$('.outsideLinkClass').click(function(e) {
var baseUrl = window.location.pathname.substring(0, window.location.pathname.indexOf('/'));
location.href = baseUrl.replace("http://", "https://") + this.attr('href');
});
The code above is untested so you will possibly have to tweak the line that assigns the baseUrl variable to get it right, but this should make it possible.

How to extract the hostname portion of a URL in JavaScript

Is there a really easy way to start from a full URL:
document.location.href = "http://aaa.bbb.ccc.com/asdf/asdf/sadf.aspx?blah"
And extract just the host part:
aaa.bbb.ccc.com
There's gotta be a JavaScript function that does this reliably, but I can't find it.
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:
Property
Result
window.location.host
sub.domain.com:8080 or sub.domain.com:80
window.location.hostname
sub.domain.com
window.location.protocol
http:
window.location.port
8080 or 80
window.location.pathname
/virtualPath
window.location.origin
http://sub.domain.com (Might include :port too*****)
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.
You could concatenate the location protocol and the host:
var root = location.protocol + '//' + location.host;
For a url, let say 'http://stackoverflow.com/questions', it will return 'http://stackoverflow.com'
The accepted answer didn't work for me since wanted to be able to work with any arbitary url's, not just the current page URL.
Take a look at the URL object:
var url = new URL("http://aaa.bbb.ccc.com/asdf/asdf/sadf.aspx?blah");
url.protocol; // "http:"
url.hostname; // "aaa.bbb.ccc.com"
url.pathname; // "/asdf/asdf/sadf.aspx"
url.search; // "?blah"
Use document.location object and its host or hostname properties.
alert(document.location.hostname); // alerts "stackoverflow.com"
There are two ways. The first is a variant of another answer here, but this one accounts for non-default ports:
function getRootUrl() {
var defaultPorts = {"http:":80,"https:":443};
return window.location.protocol + "//" + window.location.hostname
+ (((window.location.port)
&& (window.location.port != defaultPorts[window.location.protocol]))
? (":"+window.location.port) : "");
}
But I prefer this simpler method (which works with any URI string):
function getRootUrl(url) {
return url.toString().replace(/^(.*\/\/[^\/?#]*).*$/,"$1");
}
Let's suppose you have this url path:
http://localhost:4200/landing?query=1#2
So, you can serve yourself by the location values, as follow:
window.location.hash: "#2"
​
window.location.host: "localhost:4200"
​
window.location.hostname: "localhost"
​
window.location.href: "http://localhost:4200/landing?query=1#2"
​
window.location.origin: "http://localhost:4200"
​
window.location.pathname: "/landing"
​
window.location.port: "4200"
​
window.location.protocol: "http:"
window.location.search: "?query=1"
Now we can conclude you're looking for:
window.location.hostname
Try
document.location.host
or
document.location.hostname
use
window.location.origin
and for: "http://aaa.bbb.ccc.ddd.com/sadf.aspx?blah"
you will get: http://aaa.bbb.ccc.ddd.com/
There is another hack I use and never saw in any StackOverflow response :
using "src" attribute of an image will yield the complete base path of your site.
For instance :
var dummy = new Image;
dummy.src = '$'; // using '' will fail on some browsers
var root = dummy.src.slice(0,-1); // remove trailing '$'
On an URL like http://domain.com/somesite/index.html,
root will be set to http://domain.com/somesite/.
This also works for localhost or any valid base URL.
Note that this will cause a failed HTTP request on the $ dummy image.
You can use an existing image instead to avoid this, with only slight code changes.
Another variant uses a dummy link, with no side effect on HTTP requests :
var dummy = document.createElement ('a');
dummy.href = '';
var root = dummy.href;
I did not test it on every browser, though.
Check this:
alert(window.location.hostname);
this will return host name as www.domain.com
and:
window.location.host
will return domain name with port like www.example.com:80
For complete reference check Mozilla developer site.
I know this is a bit late, but I made a clean little function with a little ES6 syntax
function getHost(href){
return Object.assign(document.createElement('a'), { href }).host;
}
It could also be writen in ES5 like
function getHost(href){
return Object.assign(document.createElement('a'), { href: href }).host;
}
Of course IE doesn't support Object.assign, but in my line of work, that doesn't matter.
I would like to specify something. If someone want to get the whole url with path like I need, can use:
var fullUrl = window.location.protocol + "//" + window.location.hostname + window.location.pathname;
Regex provides much more flexibility.
//document.location.href = "http://aaa.bbb.ccc.com/asdf/asdf/sadf.aspx?blah
//1.
var r = new RegExp(/http:\/\/[^/]+/);
var match = r.exec(document.location.href) //gives http://aaa.bbb.ccc.com
//2.
var r = new RegExp(/http:\/\/[^/]+\/[^/]+/);
var match = r.exec(document.location.href) //gives http://aaa.bbb.ccc.com/asdf
My solution works in all web browsers including Microsoft Internet Explorer and doesn't use any regular expression, it's inspired of Noah Cardoza and Martin Konecny solutions:
function getHostname(href) {
if (typeof URL === 'object') {
// workaround for MS IE 11 (Noah Cardoza's solution but without using Object.assign())
var dummyNode = document.createElement('a');
dummyNode.href = href;
return dummyNode.hostname;
} else {
// Martin Konecny's solution
return new URL(href).hostname;
}
}
You can split the URL string using /
const exampleURL = "Https://exampleurl.com/page1/etc/etc"
const URLsplit = exampleURL.split("/")
console.log(URLsplit)
console.log(URLsplit[2])
Result. exampleurl.com

Categories

Resources