Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test for multiple words in a string

I have a string like so:

var str = "FacebookExternalHit and some other gibberish";

Now I have a list of strings to test if they exist in str. Here they are in array format:

var bots = ["FacebookExternalHit", "LinkedInBot", "TwitterBot", "Baiduspider"];

What is the fastest and/or shortest method to search str and see if any of the bots values are present? Regex is fine if that's the best method.

like image 395
CaribouCode Avatar asked Jul 12 '26 17:07

CaribouCode


2 Answers

Using join you can do:

var m = str.match( new RegExp("\\b(" + bots.join('|') + ")\\b", "ig") );
//=> ["FacebookExternalHit"]
like image 120
anubhava Avatar answered Jul 14 '26 06:07

anubhava


I don't know that regex is necessarily the way to go here. Check out Array.prototype.some()

var str = "FacebookExternalHit and some other gibberish";
var bots = ["FacebookExternalHit", "LinkedInBot", "TwitterBot", "Baiduspider"];
var isBot = bots.some(function(botName) {
  return str.indexOf(botName) !== -1;
});
console.log("isBot: %o", isBot);

A regular for loop is even faster:

var str = "FacebookExternalHit and some other gibberish";
var bots = ["FacebookExternalHit", "LinkedInBot", "TwitterBot", "Baiduspider"];
var isBot = false;

for (var i = 0, ln = bots.length; i < ln; i++) {
  if (str.indexOf(bots[i]) !== -1) {
    isBot = true;
    break;
  }
}

console.log("isBot: %o", isBot);
like image 31
canon Avatar answered Jul 14 '26 07:07

canon