regex that finds all the invalid emails in javascript

To find all invalid emails, you can use a regular expression in JavaScript. The regex pattern that can be used is:

index.tsx
const regexEmail = /[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/i;
61 chars
2 lines

Then you can check each email using the test() method, which returns a boolean indicating whether the email matches the pattern.

index.tsx
const emails = ['example@gmail.com', 'invalid.email@com', 'missingdomain@.com', 'missingusername@.com.', 'user.invalid.email@example.'];

const invalidEmails = emails.filter(email => !regexEmail.test(email));

console.log(invalidEmails);
// Output: ["invalid.email@com", "missingdomain@.com", "missingusername@.com."]
318 chars
7 lines

The code above creates an array of sample emails and applies the regex pattern to each one using the filter() method. The filter() method creates a new array with all elements that fail the test (i.e., don't match the pattern).

Running this code will output the array of invalid emails.

gistlibby LogSnag