根据 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.
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP