0

I have a page where admins can set up words that are blacklisted and not allowed to be used in email addresses. On the signup page, I have an array populated with all of those words. This page is internal and is for requesting multiple email addresses to be created so for each of the requested email addresses, I need to see if the word exists in the array.

I can do this with the typical jQuery inArray, however I need to figure out how to implement partial matches as well.

-- Example

var blackList = Array('admin', 'webform', 'spam');

... Loop over the requested email addresses and put them into an array

var requestedEmails = Array('dogs@cats.com', 'webform1@cats.com', 'admins@cats.com');

// Check for the exact match in the arrays
$(requestedEmails).each(function(){
    if(jQuery.inArray(this, blackList) != -1) {
        // Word is in the array
    } else {
        // Word is not in the array
    }
});

In the example above, I would need it to catch webform1 and admins as both of those words exist in the blacklist in some way.

What is the best way to add in the partial matches from here?

SBB
  • 8,560
  • 30
  • 108
  • 223
  • 2
    Possible duplicate of [How can I check if one string contains another substring?](http://stackoverflow.com/questions/1789945/how-can-i-check-if-one-string-contains-another-substring) – Craicerjack Apr 12 '16 at 14:28
  • 1
    Which jquery version are you using? If your version is high enough use grep http://api.jquery.com/jquery.grep/ – Alexander Kludt Apr 12 '16 at 14:28
  • 1.) `inArray`, 2.) loop and then compare with `substr`. 3.) use the Levenshtein distance – ST2OD Apr 12 '16 at 14:47

1 Answers1

2

there is no need using jQuery. Just plain old vanilla ES2015

check if any of the given emails in array contains blacklisted word:

var containsBlacklisted = requestedEmails
  .some(email => blackList
    .some(word => ~email.search(RegExp(word))));

filtering only emails not containing blacklisted word would be like this:

var approvedEmails = requestedEmails
  .filter(email => !blackList
    .some(word => ~email.search(RegExp(word))));
webduvet
  • 4,220
  • 2
  • 28
  • 39
  • Lol at "Plain old vanilla ES2015". I'm not sure that's an accurate description, but A+ for a good solution. – Mulan Apr 12 '16 at 15:20