How to remove or get domain name from an e-mail address in Javascript?

Sometime you have to get or remove domain name from an email address, so how can we do that in Javascript?
There are some easy ways, just write some simple functions as bellow:

For remove, we use the slice method to remove domain name:

 const getNoDomainEmail = email => {
  let noDomainEmail = null;
  const pos = email.search('@'); // get position of domain
  if (pos > 0) {
    const emailDomain = email.slice(pos); // get domain name
    noDomainEmail = email.slice(0, -(emailDomain.length)); // use the slice method to remove domain name
  }
  return noDomainEmail;
 };


Usage:

 const yourEmail = "jonth.nt49@4codev.com"
 console.log(getNoDomainEmail(yourEmail));
 // result : jonth.nt49


For get domain from your email, we use the slice method to get domain name, "+1" mean domain does not include "@":

 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;
 };


Usage:

 const yourEmail = "jonth.nt49@4codev.com"
 console.log(getDomainFromEmail(yourEmail));
 // result : 4codev.com


© 2019 4codev

Created with love by Sil.