Reputation: 3122
From an email address like [email protected]
I want to fetch domain name gmail.com
.
i want to use that pattern on textbox value in Javascript.
Pease suggest me an optimized and faster preg pattern for above requirement...
Upvotes: 24
Views: 22605
Reputation: 3193
A bit cleaner and up-to-date approach:
const email = "[email protected]"
const domain = email.includes('@') && email.split("@").pop()
Domain will be false
if email doesn't contain @ symbol.
Upvotes: 3
Reputation: 7105
var email = '[email protected]';
var domain = email.replace(/.*@/, "").split('.')[0];
console.log(domain); // gmail
Upvotes: 1
Reputation: 1
You can do this to get domain name from url,email,website,with http started,only domain name
var str=inputAddress;
var patt1 = "(http://|https://|ftp://|www.|[a-z0-9._%+-]+@)([^/\r\n]+)(/[^\r\n]*)?";
var result = str.match(patt1);
var domain=result===null?str:result[2];
return domain.toString().startsWith("www.")?domain.toString().slice(4):domain;
Upvotes: -1
Reputation: 1621
You can do this
var extract_company_name = function(email){
var temp = email.replace(/.*@/, '').split('.');
return temp[temp.length - 2];
}
extract_company_name(email)
this will fetch the domain from any email.
Upvotes: 2
Reputation: 3998
I have just experience a need to implement this and came up with the solution that combines most of already mentioned techniques:
var email = "test@[email protected]";
var email_string_array = email.split("@");
var domain_string_location = email_string_array.length -1;
var final_domain = email_string_array[domain_string_location];
So if email has multiple @ characters then you just need to split email string by "@" and calculate how many elements are there in new created array then subtract 1 from it and you can take right element from array with that number.
Here is the jsfiddle: http://jsfiddle.net/47yqn/
It has show 100% success for me!
Upvotes: 5
Reputation: 4040
Using a simple string split won't work on addresses like 'abc@abc'@example.com
which is a valid address (technically). I believe splitting on @
and taking the last element should be fine, because no @
characters are allowed to appear in the domain.
Or, since you requested, a regex:
[^@]+$
Upvotes: 4
Reputation: 5774
I would try
\b.*@([A-Za-z0-9.-]+\.[A-Za-z]{2,4})\b
Or maybe tune it a little replacing \b
s by ^
and $
.
With this you can match any domain with A-Z, a-z and 0-9 characters.
Upvotes: 1
Reputation: 10333
Why not just do this.
var email = "[email protected]", i = email.indexOf("@");
if (i != -1) {
email = email.substring(i);
}
Regex isn't really required, you could also go email = email.split("@")[1];
Upvotes: 7
Reputation: 17781
You can replace everything up to and including the @
symbol to get the domain. In Javascript:
var email = '[email protected]';
var domain = email.replace(/.*@/, "");
alert(domain);
Upvotes: 64