Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a string matches any of an array of regexes in node.js?

I'm trying to check efficiently if a string matches any of an array of regexes and return true in the first encountered match (Breaking the iteration over the regexes)

My current code:

_.forEach(self._connectedClients, function(client) {
        if (client.authenticated) {
            var interested = _.forEach(client.interests, function(interest) {
                if (evt.event_type.search(interest) != -1) {
                    return true;
                }
            });
            if (interested) {
                self._sendJSON(client.socket, data);
            }
        }
    });

Interest is an array of regexes.

Any suggestions?

Thanks in advance

like image 628
Itay Weiss Avatar asked Nov 10 '15 17:11

Itay Weiss


People also ask

How do you check if a string contains any word from an array?

You can use the includes() method in JavaScript to check if an item exists in an array. You can also use it to check if a substring exists within a string. It returns true if the item is found in the array/string and false if the item doesn't exist.


2 Answers

You could use _.some, when the function passed returns a truthy value iteration will stop and true will be returned. If it can't find a truthy value it will return false, after iterating through the entire array.

Example:

_.forEach(self._connectedClients, function(client) {
    if (client.authenticated) {
        if (_.some(client.interests, _.method('test', evt.event_type))) {
            self._sendJSON(client.socket, data);
        }
    }
});
like image 67
fuzetsu Avatar answered Nov 11 '22 03:11

fuzetsu


Just use Array#some:

some() executes the callback function once for each element present in the array until it finds one where callback returns a true value. If such an element is found, some() immediately returns true.

var interested = client.interests.some(function(regex) {
  return regex.test(evt.event_type);
});

Of course you can also use lodash's _.some implementation.

like image 28
Felix Kling Avatar answered Nov 11 '22 04:11

Felix Kling