I want to get the domain name without www
ex: https://www.gmail.com/anything Output should be gmail.com(or .net or .org)
Can anyone help me in giving a regex for this?
I want to get the domain name without www
ex: https://www.gmail.com/anything Output should be gmail.com(or .net or .org)
Can anyone help me in giving a regex for this?
Use a regex such as /(?:https?:\/\/)?(?:www\.)?(.*?)\//
:
var str = "https://www.gmail.com/anything";
var match = str.match(/(?:https?:\/\/)?(?:www\.)?(.*?)\//);
console.log(match[match.length-1]); //gmail.com (last group of the match)
Note: This will get everything after the http/https protocol, not including www - up to the first slash.
Extra note: A lot of domains use sub domains - hence mail.google.com
would suddenly become google.com
and hence not work. Mine includes every subdomain apart from www
.
You can use a <a>
to get information about a URL. For example:
var a = document.createElement("a");
a.href = "http://www.google.com";
You can retrieve the domain with:
var domain = a.hostname;
And you can strip away any leading "www.":
domain = domain.replace(/^www\./, "");
As a reusable function, you could use:
function getDomain(url) {
var a, domain;
a = document.createElement("a");
a.href = url;
domain = a.hostname;
domain = domain.replace(/^www\./, "");
return domain;
}
DEMO: http://jsfiddle.net/DuK6D/
More info/attributes about the HTMLAnchorElement JS object on MDN