Javascript jQuery:在字符串中查找数组元素 [英] Javascript jQuery: find array elements within a string
问题描述
我认为我的问题相当简单,但我对Javascript不是很有经验。我想要做的是拉取页面的源代码并将其全部添加到变量中:
I think my question is fairly straightforward but I'm not very experienced with Javascript. What I am trying to do is pull the source code of a page and stick it all into a variable:
var sourcecode = document.documentElement.innerHTML;
然后我有一系列我想搜索该变量的术语:
Then I have an array of terms that I want to search that variable for:
var array = ['Huskers','Redskins','Texans','Rockets'];
我想将0分配给<中找不到的任何数组元素code> sourcecode 变量和1到任何。因此,当搜索完成时,每个数组元素将由一个等于1或0的变量表示。任何人都可以给我一个关于我应该怎么做的提示?
I would like to assign a 0 to any of the array elements that aren't found in the sourcecode
variable and a 1 to any that are. So, when the search is complete each array element will be represented by a variable that will either equal 1 or 0. Can anyone please give me a hint as to how I should go about this?
谢谢!
推荐答案
有点神秘但做你需要的事情:
A bit cryptic but does what you need:
var source = 'lorem hello foo bar world';
var words = ['hello','red','world','green'];
words = words.map(function(w){ return +!!~source.indexOf(w) });
console.log(words); //=> [1, 0, 1, 0]
+ !!〜
转换 indexOf
返回的值的多个布尔表示形式,与:
+!!~
casts a number of the boolean representation of the value returned by indexOf
, same as:
return source.indexOf(w) == -1 ? 0 : 1;
但有点短。
注意 indexOf
匹配字符串中的字符串,如果要匹配整个单词,可以使用带有字边界的正则表达式 \b
:
Note that indexOf
matches strings within strings as well, if you want to match whole words you can use regex with word boundaries \b
:
words = words.map(function(w) {
return +new RegExp('\\b'+ w +'\\b','gi').test(source);
});
这篇关于Javascript jQuery:在字符串中查找数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!