根据JavaScript中的单词数组替换句子中所有出现的特定单词
我们需要编写一个包含字符串和字符串数组的JavaScript函数。
我们的函数应该返回一个新的字符串,该字符串中出现在数组中的单词的所有出现都由空格代替。
我们的函数应使用String.prototype.replace()方法来解决此问题。
示例
为此的代码将是-
var excludeWords = ["A", "ABOUT", "ABOVE", "ACROSS", "ALL", "ALONG", "AM",
"AN", "AND", "ANY", "ASK", "AT", "AWAY", "CAN", "DID", "DIDN'T", "DO",
"DON'T", "FOR", "FROM", "HAD", "HAS", "HER", "HIS", "IN", "INTO", "IS",
"IT", "NONE", "NOT", "OF", "ON", "One", "OUT", "SO", "SOME", "THAT",
"THE", "THEIR", "THERE", "THEY", "THESE", "THIS", "TO", "TWIT", "WAS",
"WERE", "WEREN'T", "WHICH", "WILL", "WITH", "WHAT", "WHEN", "WHY"];
var sentence = "The first solution does not work for any UTF-8 alphaben. I
have managed to create function which do not use RegExp and use good UTF-8
support in JavaScript engine. The idea is simple if symbol is equal in
uppercase and lowercase it is special character. The only exception is
made for whitespace.";
const removeExcludedWords = (str, words) => {
let sentence = '';
const regex = new RegExp(`\\b(${words.join('|')})\\b`, 'gi');
sentence = str.replace(regex, "");
return sentence;
};
console.log(removeExcludedWords(sentence, excludeWords));输出结果
控制台中的输出-
first solution does work UTF-8 alphaben. I have managed create function use RegExp use good UTF-8 support JavaScript engine. idea simple if symbol equal uppercase lowercase special character. only exception made whitespace.
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短