Javascript 如何从字符串中提取与禁止字数组中包含的字相匹配的字(并删除任何剩余的空白)?
如果给定一组禁止使用的单词,如何从字符串中提取某些单词 以Woody Allen的以下引用为例:Javascript 如何从字符串中提取与禁止字数组中包含的字相匹配的字(并删除任何剩余的空白)?,javascript,string,sanitization,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",
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
var quote=“爱是答案,但当你等待答案时,性会提出一些很好的问题”;
var probled=新数组(“is”、“the”、“but”、“you”、“are”、“for”、“the”、“some”、“pretty”);
var isprobled={};
var i;
对于(i=0;i<0.length;i++){
isForbidden[i]]=true;
}
var words=quote.split(“”);
var-sanitaryWords=[];
对于(i=0;i
var quote=“爱是答案,但当你在等待答案时,性会提出一些很好的问题”;
var probled=新数组(“is”、“the”、“but”、“you”、“are”、“for”、“the”、“some”、“pretty”);
var isprobled={};
var i;
对于(i=0;i<0.length;i++){
isForbidden[i]]=true;
}
var words=quote.split(“”);
var-sanitaryWords=[];
对于(i=0;i
试试看:
试试看:
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(" "));
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, ''));