From 8cb34e56ba752bab2a18d1f33a3beb2ee5e74363 Mon Sep 17 00:00:00 2001 From: Lan Hui <1348141770@qq.com> Date: Tue, 2 Aug 2022 12:26:18 +0800 Subject: [PATCH] Refactor: remove duplicate code block --- app/static/js/highlight.js | 24 +++++++----------------- 1 file changed, 7 insertions(+), 17 deletions(-) diff --git a/app/static/js/highlight.js b/app/static/js/highlight.js index 1c7d4fb..8a48cd9 100644 --- a/app/static/js/highlight.js +++ b/app/static/js/highlight.js @@ -25,23 +25,13 @@ function highLight() { let articleContent = document.getElementById("article").innerText; 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 - if (pickedWords != null) { - const list = pickedWords.value.split(" "); - for (let i = 0; i < list.length; ++i) { - list[i] = list[i].replace(/(^\s*)|(\s*$)/g, ""); //消除单词两边的空字符 - if (list[i] !== "" && "".indexOf(list[i]) === -1 && "".indexOf(list[i]) === -1) { - //将文章中所有出现该单词word的地方改为:" " + word + " "。 正则表达式RegExp()中,"\\s"代表单词前后必须要有空格,以防止只对单词中的部分字符高亮的情况出现。 - articleContent = articleContent.replace(new RegExp("\\s"+list[i]+"\\s", "g"), " " + list[i] + " "); - } - } - } - 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] !== "" && "".indexOf(list2[i]) === -1 && "".indexOf(list2[i]) === -1) { - articleContent = articleContent.replace(new RegExp("\\s"+list2[i]+"\\s", "g"), " " + list2[i] + " "); - } + let allWords = pickedWords.value + " " + dictionaryWords.value; + const list = allWords.split(" "); + for (let i = 0; i < list.length; ++i) { + list[i] = list[i].replace(/(^\s*)|(\s*$)/g, ""); //消除单词两边的空字符 + if (list[i] !== "" && "".indexOf(list[i]) === -1 && "".indexOf(list[i]) === -1) { + //将文章中所有出现该单词word的地方改为:" " + word + " "。 正则表达式RegExp()中,"\\s"代表单词前后必须要有空格,以防止只对单词中的部分字符高亮的情况出现。 + articleContent = articleContent.replace(new RegExp("\\s"+list[i]+"\\s", "g"), " " + list[i] + " "); } } document.getElementById("article").innerHTML = articleContent;