ComputerLocus
ComputerLocus

Reputation: 3618

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.

Upvotes: 0

Views: 86

Answers (4)

Andris Leduskrasts
Andris Leduskrasts

Reputation: 1230

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.]*?@[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.

Upvotes: 1

Thomas Weglinski
Thomas Weglinski

Reputation: 1094

One-liner:

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

Upvotes: 0

spectacularbob
spectacularbob

Reputation: 3218

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

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

Upvotes: 1

corvid
corvid

Reputation: 11187

Something like this?

/^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[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])?)*$/

Upvotes: 0

Related Questions