如何从字符串中提取匹配禁止字数组中的单词(并删除任何遗留的空格)?

时间:2010-12-18 18:15:19

标签: javascript string sanitization

在给定一系列禁用词的情况下,如何从字符串中提取某些单词。

以下面的Woody Allen引用为例:

Love is the answer, 
but while you are waiting for the answer 
sex raises some pretty good questions

这是从字符串中提取的单词数组:

var forbidden = new Array("is", "the", "but", "you", 
"are", "for", "the", "some", "pretty");

如何从字符串中提取任何单词,删除任何剩余的空格,以便最终得到此结果:

Love answer, while waiting answer sex raises good questions

2 个答案:

答案 0 :(得分:4)

 var quote = "Love is the answer, but while you are waiting for the answer sex raises some pretty good questions";
 var forbidden = new Array("is", "the", "but", "you", "are", "for", "the", "some", "pretty");

 var isForbidden = {};
 var i;

 for (i = 0; i < forbidden.length; i++) {
     isForbidden[forbidden[i]] = true;
 }

 var words = quote.split(" ");
 var sanitaryWords = [];

 for (i = 0; i < words.length; i++) {
     if (!isForbidden[words[i]]) {
          sanitaryWords.push(words[i]);
     }
 }

 alert(sanitaryWords.join(" "));

答案 1 :(得分:2)

var quote = "Love is the answer,\nbut while you are waiting for the answer\nsex raises some pretty good questions";

var forbidden = ["is", "the", "but", "you", "are", "for", "the", "some", "pretty"];

var reg = RegExp('\\b(' + forbidden.join('|') + ')\\b\\s?', 'g');

alert(quote.replace(reg, ''));

试一试: http://jsbin.com/isero5/edit