Reputation: 1
How would you extract certain words from a string, given an array of forbidden words.
Consider the following Woody Allen quote as an example:
Love is the answer,
but while you are waiting for the answer
sex raises some pretty good questions
And this is the array of words to extract from the string:
var forbidden = new Array("is", "the", "but", "you",
"are", "for", "the", "some", "pretty");
How would you extract any words from the string, any remove any left-over whitespace so that you end up with this result:
Love answer, while waiting answer sex raises good questions
Upvotes: 0
Views: 821
Reputation: 48260
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, ''));
Try it: http://jsbin.com/isero5/edit
Upvotes: 2
Reputation: 14337
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(" "));
Upvotes: 4