JAVASCRIPT
Validate and Parse Email Addresses with Regex
Validate email addresses and deconstruct them into username and domain components using a concise JavaScript regex pattern with capture groups.
function parseEmail(email) {
const emailRegex = /^([a-zA-Z0-9._%+-]+)@([a-zA-Z0-9.-]+\.[a-zA-Z]{2,})$/;
const match = emailRegex.exec(email);
if (match) {
return {
isValid: true,
username: match[1],
domain: match[2]
};
} else {
return {
isValid: false
};
}
}
// Examples:
console.log(parseEmail("[email protected]"));
/*
{
isValid: true,
username: 'user.name+tag',
domain: 'example.co.uk'
}
*/
console.log(parseEmail("invalid-email")); // { isValid: false }
How it works: This JavaScript snippet uses regex to both validate an email address and extract its username and domain parts. The pattern `^([a-zA-Z0-9._%+-]+)@([a-zA-Z0-9.-]+\.[a-zA-Z]{2,})$` uses two capture groups: the first for the part before the '@' (`username`), and the second for the part after the '@' (`domain`). The `exec()` method returns an array containing the full match and captured groups, allowing easy access to the parsed components. If no match is found, it returns `null`.