Strip contact information from email

I sometimes have users enter emails like:

John Smith <[email protected]>

I have a regex like /(.+[ <>])/g but this is not correct for this.

I would like to have an output like:

[email protected]

I only want the email component, and want to ignore anything else a user may give.

Edit: People are getting confused. I simply want the input to turn out like the output. This has nothing to do with validation. I already have validation. This has to do with cleaning the input before it even gets to the validation.


Assuming an e-mail for your input always has an "@" symbol, you can select the single token your e-mail makes with the symbols you'd like to accept. For example:

[A-Za-z0-9.]*[email protected][A-Za-z0-9.]*

test test test john [email protected] test

will result in

[email protected]

E-mails can contain dashes and underscores ([email protected]), so consider adding them into the [A-Za-z0-9.] character class, making it [A-Za-z0-9.\-_], or whatever characters you feel are appropriate.

Perhaps this will work, though you may want to modify it a little according to which characters you want to allow in an email address

<(\[email protected][a-zA-Z_]+?\.[a-zA-Z]{2,3})>

Something like this?

/^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-][email protected][a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/


var str = "John Smith <[email protected]>",
mail = /[^<>]+/g.exec(/<.+>/g.exec(str))[0];

Category:javascript Time:2018-11-04 Views:9

Related post

Copyright (C), All Rights Reserved.

processed in 0.368 (s). 13 q(s)