我有一组字符串关键字和一组数组列表,用于比较和排除最终字符串显示中的项目。我插入了一个拆分来隔离每个字符串。
以下是代码:
var keywords = "Did the cow jump over the moon?";
var keywords_parsed = keywords.split(" ");
var exclusionlist = ["a","is","of","in","on","it","to","if","so","the","i","we","did"];
最后的字符串显示应为
cow, jump, over, moon
代码应排除“Did”,“the”和其他“the”。
我该如何做到这一点?
答案 0 :(得分:0)
这是一个oneliner,只是为了好玩:
keywords.match(/\w+/g)
.map(function(i) {return i.toLowerCase();})
.filter(function(i) { return exclusionlist.indexOf(i) == -1; })
JSFiddle:http://jsfiddle.net/4KSKQ/
答案 1 :(得分:0)
您正在寻找javascript array filter方法。你可以做这样的事情来达到你想要的目的。
var keywords = "Did the cow jump over the moon?";
// change lowercase then split the words into array
var keywords_parsed = keywords.toLowerCase().split(" ");
var exclusionlist = ["a","is","of","in","on","it","to","if","so","the","i","we","did"];
// now filter out the exclusionlist
keywords_parsed.filter(function(x) { return exclusionlist.indexOf(x) < 0 });