How to check if a string matches any regular expression array in node.js?

I try to check the effectiveness if the string matches any of the array of regular expressions and returns true in the first match it encounters (interrupting the iteration over regular expressions)

My current code is:

_.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 regular expressions.

Any suggestions?

Thank you in advance

+6
source share
3 answers

You can use _.some when the function passed returns the true value, the iteration stops, and true is returned. If it cannot find the true value, it will return false after iterating over 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); } } }); 
+3
source

Just use Array#some :

some() performs a callback function once for each element present in the array until it finds one where the callback returns the 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 the lodash _.some implementation.

+3
source

If I understand you correctly using simple javascript, you can do the following to check for single line matches over multiple regular expressions .

 for(var i = 0; i<x.length; i++) { var regex = x[i]; console.log('regex', regex); if( str.match( x[i] ) ) { console.log("regex:",x[i]," matching: true"); } else { console.log("regex:",x[i]," matching: false"); } } 

However, if you meant something else, then specify. :)

0
source

All Articles