简体   繁体   English

针对字符串测试子字符串数组

[英]Test array of sub strings against a string

I have an array of bot names. 我有一系列机器人名称。 When a user or bot visits my site, I get the user-agent and want to test if one of the values in my array exists in it. 当用户或漫游器访问我的网站时,我得到了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);
});

This gives me the error: TypeError: undefined is not a function 这给了我错误: TypeError: undefined is not a function

What's going wrong here? 这是怎么了 Bonus points if you can help me expand this bots list by pointing me to a helpful external link or suggesting some yourself! 如果您可以通过指向有用的外部链接或提出一些建议来帮助我扩展此机器人列表,则可获赠积分。

The test function is not available on Strings, but on RegExp objects. test功能在字符串上不可用,但是在RegExp对象上不可用。 Therefore, you need to define your blacklisted items as RegExps, not strings: 因此,您需要将列入黑名单的项目定义为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***')); 

try this: 尝试这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM