So, I have this JavaScript function:
ME.Utils = {
RxEmail: new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i),
ValidateEmail: function(email) {
return ME.Utils.RxEmail.test(email);
},
GetEmailAddresses: function(text) {
return text.match(ME.Utils.RxEmail);
},
HasEmail: function(text) {
return ME.Utils.GetEmailAddresses != null;
}
};
ValidateEmail works very well. However, HasEmail and GetEmailAddresses is not working properly.
GetEmailAdresses always returns null, except for when the string only contains an email address. In this case, GetEmailAdresses returns an array not only containing the email address, but the email address (test@test.com), just the id (test) plus some unidentified etc. etc…
Can you help me figure out what’s wrong in my expression?
There are a few problems.
Your regex is anchored at the start and end of the string. You should remove the
^and$characters from it.If you want to return only the email addresses, use non-capturing groups.
In
HasEmail(), you’re not callingGetEmailAddresses(). You’re actually checking if the value of that property is defined.All in all, a fixed version might look like: