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);
const email = "user@example.com";
const [user, domain] = email.split("@");
console.log(user); // user
console.log(domain); // example.comThis is easy to read for ordinary addresses.
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.
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) };
}
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.
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.
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
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.