Refactor: remove duplicate code block

Lan Hui 2022-08-02 12:26:18 +08:00
parent b5dacb9ad2
commit 8cb34e56ba
1 changed files with 7 additions and 17 deletions

View File

@ -25,23 +25,13 @@ function highLight() {
let articleContent = document.getElementById("article").innerText; let articleContent = document.getElementById("article").innerText;
let pickedWords = document.getElementById("selected-words"); // words picked to the text area let pickedWords = document.getElementById("selected-words"); // words picked to the text area
let dictionaryWords = document.getElementById("selected-words2"); // words appearing in the user's new words list let dictionaryWords = document.getElementById("selected-words2"); // words appearing in the user's new words list
if (pickedWords != null) { let allWords = pickedWords.value + " " + dictionaryWords.value;
const list = pickedWords.value.split(" "); const list = allWords.split(" ");
for (let i = 0; i < list.length; ++i) { for (let i = 0; i < list.length; ++i) {
list[i] = list[i].replace(/(^\s*)|(\s*$)/g, ""); //消除单词两边的空字符 list[i] = list[i].replace(/(^\s*)|(\s*$)/g, ""); //消除单词两边的空字符
if (list[i] !== "" && "<mark>".indexOf(list[i]) === -1 && "</mark>".indexOf(list[i]) === -1) { if (list[i] !== "" && "<mark>".indexOf(list[i]) === -1 && "</mark>".indexOf(list[i]) === -1) {
//将文章中所有出现该单词word的地方改为" <mark>" + word + "<mark> "。 正则表达式RegExp()中,"\\s"代表单词前后必须要有空格,以防止只对单词中的部分字符高亮的情况出现。 //将文章中所有出现该单词word的地方改为" <mark>" + word + "<mark> "。 正则表达式RegExp()中,"\\s"代表单词前后必须要有空格,以防止只对单词中的部分字符高亮的情况出现。
articleContent = articleContent.replace(new RegExp("\\s"+list[i]+"\\s", "g"), " <mark>" + list[i] + "</mark> "); articleContent = articleContent.replace(new RegExp("\\s"+list[i]+"\\s", "g"), " <mark>" + list[i] + "</mark> ");
}
}
}
if (dictionaryWords != null) {
const list2 = dictionaryWords.value.split(" ");
for (let i = 0; i < list2.length; ++i) {
list2[i] = list2[i].replace(/(^\s*)|(\s*$)/g, "");
if (list2[i] !== "" && "<mark>".indexOf(list2[i]) === -1 && "</mark>".indexOf(list2[i]) === -1) {
articleContent = articleContent.replace(new RegExp("\\s"+list2[i]+"\\s", "g"), " <mark>" + list2[i] + "</mark> ");
}
} }
} }
document.getElementById("article").innerHTML = articleContent; document.getElementById("article").innerHTML = articleContent;