测试字符串的子字符串数组

时间:2015-09-08 10:38:26

标签: javascript arrays node.js express user-agent

我有一系列机器人名称。当用户或机器人访问我的网站时,我会得到user-agent并想要测试我的数组中是否存在其中一个值。

var bots = [
  "twitterbot",
  "linkedinbot",
  "facebookexternalhit",
  "pinterest",
  "dotbot", 
  "rogerbot",
  "googlebot",
  "baiduspider",
  "yahoo! slurp",
  "bot",
  "spider",
  "simplepie",
  "yahooseeker",
  "embedly",
  "quora link preview",
  "outbrain",
  "vkshare",
  "monit",
  "pingability",
  "monitoring",
  "winhttprequest",
  "apache-httpclient",
  "getprismatic.com",
  "python-requests",
  "twurly",
  "yandex",
  "browserproxy",
  "webmeup-crawler",
  "qwantify"
];

var isBot = function(agent){
  return bots.some(function(bot){
    return bot.test(agent);      
  });
}

app.use(function(req, res, next){
  var test = isBot(req.get("user-agent").toLowerCase());
  console.log(test);
});

这给了我错误:TypeError: undefined is not a function

这里出了什么问题? 如果你可以通过指向一个有用的外部链接或自己暗示一下来帮助我扩展这个机器人列表,可以获得奖励积分!

2 个答案:

答案 0 :(得分:3)

test函数在字符串上不可用,但在RegExp对象上不可用。因此,您需要将列入黑名单的项目定义为RegExps,而不是字符串:

    var bots = [
      /twitterbot/,
      /linkedinbot/,
      /facebookexternalhit/,
      /pinterest/,
      /dotbot/,
      /rogerbot/,
      /googlebot/,
      /baiduspider/,
      /yahoo! slurp/,
      /bot/,
      /spider/,
      /simplepie/,
      /yahooseeker/,
      /embedly/,
      /quora link preview/,
      /outbrain/,
      /vkshare/,
      /monit/,
      /pingability/,
      /monitoring/,
      /winhttprequest/,
      /apache-httpclient/,
      /getprismatic.com/,
      /python-requests/,
      /twurly/,
      /yandex/,
      /browserproxy/,
      /webmeup-crawler/,
      /qwantify/
    ];
    
    var isBot = function(agent){
      return bots.some(function(bot){
        return bot.test(agent);      
      });
    };

alert('"clean-user-agent" is bot? ' + isBot('clean-user-agent'));
alert('"the ***twitterbot***" is bot? ' + isBot('the ***twitterbot***'));

答案 1 :(得分:1)

试试这个:

var bots = [
  /twitterbot/,
  /linkedinbot/,
  /facebookexternalhit/,
  /pinterest/,
  /dotbot/,
  /rogerbot/,
  /googlebot/,
  /baiduspider/,
  /yahoo! slurp/,
  /bot/,
  /spider/,
  /simplepie/,
  /yahooseeker/,
  /embedly/,
  /quora link preview/,
  /outbrain/,
  /vkshare/,
  /monit/,
  /pingability/,
  /monitoring/,
  /winhttprequest/,
  /apache-httpclient/,
  /getprismatic.com/,
  /python-requests/,
  /twurly/,
  /yandex/,
  /browserproxy/,
  /webmeup-crawler/,
  /qwantify/
];
var isBot = function(agent){
  for(var b in bots) {
    if(bot[b].test(agent)) {
      return true;
    }     
  } 
  return false;
}