find email addresses in a string using regex in javascript

To find email addresses in a string using regex in JavaScript, you can use the following regular expression pattern:

index.tsx
const emailRegex = /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g;
70 chars
2 lines

This pattern matches any sequence of characters that looks like an email address. It matches the following components:

  • [A-Za-z0-9._%+-]+: One or more alphanumeric characters, dots, underscores, percent signs, plus signs, or hyphens.
  • @: At symbol.
  • [A-Za-z0-9.-]+: One or more alphanumeric characters, dots, or hyphens.
  • \.: Escaped dot.
  • [A-Za-z]{2,}: Two or more consecutive letters.

The g flag at the end of the regular expression enables global searching, which means it will find all matches in the input string.

Here's an example of using this regular expression to find email addresses in a string:

index.tsx
const input = 'Email me at user@example.com or contact@example.org';
const emailRegex = /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g;
const matches = input.match(emailRegex);

console.log(matches); // Output: ['user@example.com', 'contact@example.org']
258 chars
6 lines

This code finds all email addresses in the input string and stores them in the matches array.

gistlibby LogSnag