比较和排除数组列表中的字符串关键字

时间:2014-05-21 01:38:18

标签: javascript arrays string arraylist match

我有一组字符串关键字和一组数组列表,用于比较和排除最终字符串显示中的项目。我插入了一个拆分来隔离每个字符串。

以下是代码:

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”。

我该如何做到这一点?

2 个答案:

答案 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 });
相关问题