根據 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