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.
- 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
2 Answers
Reset to default 5Using 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
版权声明:本文标题:javascript - Test for multiple words in a string - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741584767a2386779.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论