我有一个像这样的字符串:
var str = "FacebookExternalHit and some other gibberish";
现在我有一个要测试的字符串列表,如果它们存在于str
中。这里是数组格式:
var bots = ["FacebookExternalHit", "LinkedInBot", "TwitterBot", "Baiduspider"];
搜索str
并查看是否存在任何bots
值的最快和/或最短的方法是什么?如果这是最好的方法,正则表达式很好。
答案 0 :(得分:3)
使用join
即可:
var m = str.match( new RegExp("\\b(" + bots.join('|') + ")\\b", "ig") );
//=> ["FacebookExternalHit"]
答案 1 :(得分:3)
我不知道正则表达式一定是去这里的方式。查看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);

常规for
循环为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);
&#13;