Here is an example of a regular expression (regex) for email validation using JavaScript:
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
This regex checks whether a string is a valid email address or not. Here’s a breakdown of how it works:
^
indicates the start of the string.[^\s@]+
matches one or more characters that are not whitespace or@
.@
matches the@
character.[^\s@]+
matches one or more characters that are not whitespace or@
.\.
matches a literal dot (.
).[^\s@]+
matches one or more characters that are not whitespace or@
.$
indicates the end of the string.
In plain English, this regex checks whether the string starts with one or more characters that are not whitespace or @
, followed by an @
character, followed by one or more characters that are not whitespace or @
, followed by a dot (.
), followed by one or more characters that are not whitespace or @
, and ends with one or more characters that are not whitespace or @
.
You can use this regex with the test()
method to check whether a string is a valid email address or not:
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const email = 'john.doe@example.com';
const isValidEmail = emailRegex.test(email);
console.log(isValidEmail); // true
In this example, we create a regex emailRegex
and a string email
that contains a valid email address. We then use the test()
method of the emailRegex
object to check whether the email
string is a valid email address or not. Finally, we log the result to the console (true
, in this case).
0 Comments