check if a string is email in javascript

To check if a string is an email in JavaScript, you can use regular expressions (regex). Here's an example code:

index.tsx
function isValidEmail(email) {
  const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return regex.test(email);
}

// usage
console.log(isValidEmail('test@example.com')); // true
console.log(isValidEmail('some text')); // false
221 chars
9 lines

The isValidEmail() function takes an email string as an argument and returns true if the string matches the email format, otherwise false. The regular expression /^[^\s@]+@[^\s@]+\.[^\s@]+$/ checks if the string starts with one or more characters that are not whitespace or @, followed by @, followed by one or more characters that are not whitespace or @, followed by ., and ends with one or more characters that are not whitespace or @.

related categories

gistlibby LogSnag