admin管理员组

文章数量:1293605

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.

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.

Share Improve this question asked Mar 25, 2015 at 18:06 CaribouCodeCaribouCode 14.4k33 gold badges111 silver badges185 bronze badges 6
  • 2 Just loop over the array. – Andy Commented Mar 25, 2015 at 18:09
  • Yeh I thought about doing that but it occurred to me there might be a shorted and easier way. – CaribouCode Commented Mar 25, 2015 at 18:11
  • A simple white-list, though I'm not sure how fast it is pared to a loop. – Teemu Commented Mar 25, 2015 at 18:16
  • 2 @teemu here's a test. It's pretty biased, though... considering the input string... – canon Commented Mar 25, 2015 at 19:10
  • 1 @Teemu I've updated to include a cached regex test (which obviously performs better). That said, in practice he's going to have to instantiate the regex. That overhead should be considered. If the OP actually stands to re-use the regex it makes more sense. Without more information, though... I couldn't say. – canon Commented Mar 25, 2015 at 19:25
 |  Show 1 more ment

2 Answers 2

Reset to default 5

Using join you can do:

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

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

本文标签: javascriptTest for multiple words in a stringStack Overflow