Get Username and Domain from an Email Address in JavaScript

For a simple, already-validated address, find the last @ and split the string into the local part and domain. Do not treat this simple parsing step as complete email validation.

const email = "user@example.com";
const at = email.lastIndexOf("@");
const user = email.slice(0, at);
const domain = email.slice(at + 1);
console.log(user, domain);

Split a simple address Top ↑

const email = "user@example.com";
const [user, domain] = email.split("@");
console.log(user);   // user
console.log(domain); // example.com

This is easy to read for ordinary addresses.

Use lastIndexOf() and slice() Top ↑

const email = "name@example.co.in";
const at = email.lastIndexOf("@");
const user = email.slice(0, at);
const domain = email.slice(at + 1);

This connects to slice() and index searching.

Basic defensive checks Top ↑

function getEmailParts(email) {
  const at = email.lastIndexOf("@");
  if (at <= 0 || at === email.length - 1) return null;
  return { user: email.slice(0, at), domain: email.slice(at + 1) };
}

Work with domain labels Top ↑

const domain = "mail.example.co.in";
const labels = domain.split(".");
console.log(labels);

Do not assume the final two labels always represent the registrable domain; public suffix rules are more complex.

Parsing is not full email validation Top ↑

Real email-address syntax is more complex than checking for one @. For forms, combine browser validation such as type='email' with server-side validation. Plus2net also has a PHP email-part example.

Privacy and security Top ↑

Avoid logging or exposing email addresses unnecessarily. If the address is submitted to a server, validate and handle it there as untrusted input.

Previous / String Reference Next related topic




Subscribe to our YouTube Channel here



plus2net.com










✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer