find email inside string with regex in javascript

To find an email within a string using regex in JavaScript, we can write the following code:

index.tsx
const string = "Please contact me at testemail@example.com for more information.";

const emailPattern = /\b[\w\.-]+@[\w\.-]+\.\w{2,}\b/;

const email = string.match(emailPattern)[0];

console.log(email);
205 chars
8 lines

In this example, we define a string that contains an email. We then define our regex pattern to match an email using the regular expression syntax. Finally, we use the match() function on the string string to find the match for the email pattern. The [0] at the end of match() returns the first match found, which in this case is the email.

The output of this code will be the email testemail@example.com.

gistlibby LogSnag