April 15, 2023

Regular expression to validate email in Javascript

javascript
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const email = "example.email@domain.com";
if (emailRegex.test(email)) {
console.log("Valid email address");
} else {
console.log("Invalid email address");
}

In this example, we have defined the emailRegex
regular expression as /^[^\s@]+@[^\s@]+\.[^\s@]+$/.
We then define an email address as example.email@domain.com.

We use the test method of the regular expression object to check whether the email address matches the regular expression pattern. If it does, we log "Valid email address". If it doesn't, we log "Invalid email address".

In this case, the email address "example.email@domain.com" matches the regular expression pattern and the output will be "Valid email address".