@@ -3,6 +3,7 @@ import { alphaNumericAndMarksCharsStr, domainNameCharRegex } from "../regex-lib"
33import { EmailMatch } from "../match/email-match" ;
44import { Match } from "../match/match" ;
55import { throwUnhandledCaseError } from '../utils' ;
6+ import { tldRegex } from "./tld-regex" ;
67
78// For debugging: search for other "For debugging" lines
89// import CliTable from 'cli-table';
@@ -23,6 +24,12 @@ export class EmailMatcher extends Matcher {
2324 */
2425 protected localPartCharRegex = new RegExp ( `[${ alphaNumericAndMarksCharsStr } !#$%&'*+/=?^_\`{|}~-]` ) ;
2526
27+ /**
28+ * Stricter TLD regex which adds a beginning and end check to ensure
29+ * the string is a valid TLD
30+ */
31+ protected strictTldRegex = new RegExp ( `^${ tldRegex . source } $` ) ;
32+
2633 /**
2734 * Valid URI scheme for email address URLs
2835 */
@@ -35,6 +42,7 @@ export class EmailMatcher extends Matcher {
3542 parseMatches ( text : string ) {
3643 const tagBuilder = this . tagBuilder ,
3744 localPartCharRegex = this . localPartCharRegex ,
45+ strictTldRegex = this . strictTldRegex ,
3846 mailToScheme = this . mailToScheme ,
3947 matches : Match [ ] = [ ] ,
4048 len = text . length ,
@@ -214,6 +222,19 @@ export class EmailMatcher extends Matcher {
214222 currentEmailAddress = noCurrentEmailAddress
215223 }
216224
225+ /**
226+ * Determines if the given email address has a valid TLD or not
227+ * @param {string } emailAddress - email address
228+ * @return {Boolean } - true is email have valid TLD, false otherwise
229+ */
230+ function doesEmailHaveValidTld ( emailAddress : string ) {
231+ const emailAddressTld : string = emailAddress . split ( '.' ) . pop ( ) || '' ;
232+ const emailAddressNormalized = emailAddressTld . toLowerCase ( ) ;
233+ const isValidTld = strictTldRegex . test ( emailAddressNormalized ) ;
234+
235+ return isValidTld ;
236+ }
237+
217238
218239 /*
219240 * Captures the current email address as an EmailMatch if it's valid,
@@ -244,12 +265,15 @@ export class EmailMatcher extends Matcher {
244265 matchedText = text . slice ( offset , charIdx ) ;
245266 }
246267
247- matches . push ( new EmailMatch ( {
248- tagBuilder : tagBuilder ,
249- matchedText : matchedText ,
250- offset : offset ,
251- email : emailAddress
252- } ) ) ;
268+ // if the email address has a valid TLD, add it to the list of matches
269+ if ( doesEmailHaveValidTld ( emailAddress ) ) {
270+ matches . push ( new EmailMatch ( {
271+ tagBuilder : tagBuilder ,
272+ matchedText : matchedText ,
273+ offset : offset ,
274+ email : emailAddress
275+ } ) ) ;
276+ }
253277 }
254278
255279 resetToNonEmailAddressState ( ) ;
0 commit comments