[英]Check if any word in string is in an array
I have a gigantic list (800 items) and one really long string. 我有一个巨大的清单(800个项目)和一个很长的字符串。 I want to get the first item in the array that matches the part of the string and stored in a variable.
我想获取数组中与字符串部分匹配并存储在变量中的第一项。
My code currently: 我的代码当前:
for (var i = 0; i<gigantic_genre_array.length; i++) {
var test_genre = thelongstr.indexOf(gigantic_genre_array[i]);
if(test_genre != -1) {
tag1 = gigantic_genre_array[test_genre];
alert(tag1);
}
}
This doesn't work like I thought it would, any suggestions? 这不像我想的那样有效,有什么建议吗?
Try this: 尝试这个:
for(var i = 0; i<gigantic_genre_array.length; i++){
var test_genre = thelongstr.indexOf(gigantic_genre_array[i]);
if(test_genre!=-1){
tag1 = gigantic_genre_array[i];
alert(tag1);
}
}
Do the process reversely it will be efficient too. 反向执行该过程也将非常有效。
var wordArray = thelongstr.split(' ');
for(var i=0,len = wordArray.length; i < len; i++)
{
if(gigantic_genre_array.indexOf(wordArray[i]) > -1)
{
alert(wordArray[i]);
}
}
You may create a RegExp based on the array and test it against the string: 您可以基于数组创建RegExp并针对字符串进行测试:
var gigantic_genre_array=['foo','bar','foobar'];
var thelongstr='where is the next bar';
alert(new RegExp(gigantic_genre_array.join('|')).exec(thelongstr)||[null][0]);
//returns bar
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.