更新时间:2023-02-19 12:27:38
有点神秘但做你需要的事情:
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);
});