CaribouCode
CaribouCode

Reputation: 14398

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.

Upvotes: 3

Views: 8950

Answers (2)

canon
canon

Reputation: 41675

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);

Upvotes: 5

anubhava
anubhava

Reputation: 785156

Using join you can do:

var m = str.match( new RegExp("\\b(" + bots.join('|') + ")\\b", "ig") );
//=> ["FacebookExternalHit"]

Upvotes: 5

Related Questions