49

With javascript, how do we remove the @gmail.com or @aol.com from a string so that what only remains is the name?

var string = "johndoe@yahoo.com";

Will be just "johdoe"? I tried with split but it did not end well. thanks.

Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
leeshin
  • 1,043
  • 5
  • 15
  • 30
  • 4
    What was the problem you had with `split('@')`? – icedwater Aug 22 '13 at 04:33
  • 2
    @icedwater the problem with `.split('@')` is that `@` is allowed as part of the *name/address* like in `im@home@example.com` - in that case `split` cannot guarantee that the `[0]`th result is the actual full string name `im@home` but will rather result in only `im`. – Roko C. Buljan Jan 03 '17 at 20:47

8 Answers8

103
var email = "john.doe@example.com";
var name   = email.substring(0, email.lastIndexOf("@"));
var domain = email.substring(email.lastIndexOf("@") +1);

console.log( name );   // john.doe
console.log( domain ); // example.com

The above will also work for valid names containing @ (tools.ietf.org/html/rfc3696Page 5):

john@doe
"john@@".doe
"j@hn".d@e

Using RegExp:

Given the email value is already validated, String.prototype.match() can be than used to retrieve the desired name, domain:

String match:

const name   = email.match(/^.+(?=@)/)[0];    
const domain = email.match(/(?<=.+@)[^@]+$/)[0]; 

Capturing Group:

const name   = email.match(/(.+)@/)[1];    
const domain = email.match(/.+@(.+)/)[1];

To get both fragments in an Array, use String.prototype.split() to split the string at the last @ character:

const [name, domain] = email.split(/(?<=^.+)@(?=[^@]+$)/);
console.log(name, domain);

or simply with /@(?=[^@]*$)/.
Here's an example that uses a reusable function getEmailFragments( String )

const getEmailFragments = (email) => email.split(/@(?=[^@]*$)/);

[ // LIST OF VALID EMAILS:
  `info@example.com`,
  `john@doe@example.com`,
  `"john@@".doe@example.com`,
  `"j@hn".d@e@example.com`,
]
.forEach(email => {
  const [name, domain] = getEmailFragments(email);
  console.log("DOMAIN: %s NAME: %s ", domain, name);
});
Community
  • 1
  • 1
Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
  • 1
    yeah, it worked. i did not know it was as simple as that. thanks! – leeshin Aug 22 '13 at 03:48
  • *Make sure you don't name the variable `String` (with a capital "S"). Not trying to be pedantic, but it's a reserved keyword. – Gary Aug 22 '13 at 03:52
  • My comment would have been more appropriate on the question rather than your answer – Gary Aug 22 '13 at 04:02
  • multiple @ in an email is valid, http://haacked.com/archive/2007/08/21/i-knew-how-to-validate-an-email-address-until-i.aspx/ – Aun Rizvi Apr 24 '15 at 06:39
11

You should take note that a valid email address is an incredibly sophisticated object and may contain multiple @ signs (ref. http://cr.yp.to/im/address.html).

"The domain part of an address is everything after the final @."

Thus, you should do something equivalent to:

var email = "johndoe@yahoo.com";
var name = email.substring(0, email.lastIndexOf("@"));

or even shorter,

var name = email.replace(/@[^@]+$/, '');

If you want both the name and the domain/hostname, then this will work:

var email = "johndoe@yahoo.com";
var lasta = email.lastIndexOf('@');
var name, host;
if (lasta != -1) {
    name = email.substring(0, lasta);
    host = email.substring(lasta+1);
    /* automatically extends to end of string when 2nd arg omitted */
} else {
    /* respond to invalid email in some way */
}
Joseph Myers
  • 6,434
  • 27
  • 36
  • an email address might contain another `@` if included in `""` quotes. http://tools.ietf.org/html/rfc3696 `These quoted forms are rarely recommended, and are uncommon in practice` http://i.imgur.com/SfgsLuN.jpg – Roko C. Buljan Aug 22 '13 at 04:53
  • 1
    @RokoC.Buljan Your screenshot of Gmail is irrelevant. It has always been up to each host to define and validate its own mailbox identifier format within the broad range defined by documents dating many years before the one that you cite. Even the one you cite states the same thing: "... they should not be rejected in filtering routines but, [sic] should instead be passed to the email system for evaluation by the destination host." Also, you didn't finish the quote: "**rarely used in practice, but are required for some legitimate purposes**." – Joseph Myers Aug 22 '13 at 04:57
  • @RokoC.Buljan Re my previous comment. The paragraph you quoted is slightly different from the one I thought you quoted, but even the one you quoted goes on to say this: "and are uncommon in practice, but, as discussed above, **must be supported by applications that are processing email addresses**." – Joseph Myers Aug 22 '13 at 05:02
  • 1
    Yum, I did a bit more research on that matter, and thanks for posting the additional information I skipped. +1 any way. Also to mention if `lastIndexOf` is supported by browser (`ECMA-262`) – Roko C. Buljan Aug 22 '13 at 05:45
9

And another alternative using split:

var email = "john.doe@email.com";
var sp = email.split('@');

console.log(sp[0]); // john.doe
console.log(sp[1]); // email.com
Wtower
  • 18,848
  • 11
  • 103
  • 80
  • 1
    You'd rather take the last element of `sp` instead of the second as, as mentioned by @joseph-myers , "The domain part of an address is everything after the final @.". You can use `email.split('@').pop()` for that. – Raphaël Jul 22 '19 at 15:13
4

Try it using substring() and indexOf()

var name = email.substring(0, email.indexOf("@"));
Atish Kumar Dipongkor
  • 10,220
  • 9
  • 49
  • 77
1
var email = "johndoe@yahoo.com";
email=email.replace(/@.*/,""); //returns string (the characters before @)
0

You can try with the replace() and regular expression. You can read more about replace() using regex here

var myEmail = 'johndoe@yahoo.com';
var name= myEmail.replace(/@.*/, "");
console.log(name);

This returns the string before @

Khurshid Ansari
  • 4,638
  • 2
  • 33
  • 52
Manoj Kadolkar
  • 717
  • 8
  • 22
0

As shown in How to remove or get domain name from an e-mail address in Javascript?, you can do it using the following code:

const getDomainFromEmail = email => {
  let emailDomain = null;
  const pos = email.search('@'); // get position of domain
  if (pos > 0) {
    emailDomain = email.slice(pos+1); // use the slice method to get domain name, "+1" mean domain does not include "@"
  }
  return emailDomain;
 };
const yourEmail = "jonth.nt49@4codev.com"
 console.log(getDomainFromEmail(yourEmail));
 // result : 4codev.com
Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
-1

This simple regex will do the needful.
/^.*(?=@)/g.

Example:

"johndoe@yahoo.com".match(/^.*(?=@)/g); // returns Array [ "johndoe" ]
Omkar Kulkarni
  • 1,091
  • 10
  • 22