From eb3268a1391bf8bb3bca842d2533be05af4ffad6 Mon Sep 17 00:00:00 2001
From: KangyangLu <1743527376@qq.com>
Date: Sat, 6 Jul 2024 16:34:54 +0800
Subject: [PATCH] Fix bug 579
---
app/static/js/highlight.js | 54 ++++++++++++++++++++++++++++++++++++--
1 file changed, 52 insertions(+), 2 deletions(-)
diff --git a/app/static/js/highlight.js b/app/static/js/highlight.js
index 9646ff3..4552e9d 100644
--- a/app/static/js/highlight.js
+++ b/app/static/js/highlight.js
@@ -15,6 +15,42 @@ function showBtnHandler() {
document.getElementById("text-content").addEventListener("touchstart", fillInWord, false);
highLight();
}
+function replaceWords(str, word) {
+ let count = 0;
+
+ const regex = new RegExp(`(^|\\s)${word}(?=\\s|$)`, 'g');
+
+ let result = str.replace(regex, (match, p1) => {
+ count++;
+ // p1 保留前导空格(如果有),仅第一个匹配保留,后续匹配替换为空字符串
+ return count === 1 ? match : p1;
+ });
+
+ return result;
+}
+
+function countWords(str, word) {
+ // 使用正则表达式匹配目标单词的整个单词边界情况,包括前后空格、行首和行尾
+ const regex = new RegExp(`(^|\\s)${word}(?=\\s|$)`, 'g');
+ let match;
+ let count = 0;
+
+ // 迭代匹配所有符合条件的单词
+ while ((match = regex.exec(str)) !== null) {
+ count++;
+ }
+
+ return count;
+}
+//用于替换单词
+function replaceAllWords(str, word, replacement) {
+ const regex = new RegExp(`(^|\\s)${word}(?=\\s|$)`, 'gi');
+ let result = str.replace(regex, (match, p1) => {
+ return p1 + replacement;
+ });
+
+ return result;
+}
function getWord() {
return window.getSelection ? window.getSelection() : document.selection.createRange().text;
@@ -33,8 +69,22 @@ function highLight() {
if(word !== null && word !== "" && word !== " "){
let articleContent_fb2 = articleContent;
if(localStorage.getItem("nowWords").indexOf(word) !== -1 || localStorage.getItem("nowWords").indexOf(word.toLowerCase()) !== -1){
- articleContent = articleContent.replace(new RegExp('' + word + '', "gi"), word);
- pickedWords.value = localStorage.getItem("nowWords").replace(word,"");
+ articleContent = articleContent.replace(new RegExp('' + word + '', "g"), word);
+
+ let count=countWords(pickedWords.value,word)
+ let currentWords=localStorage.getItem("nowWords")+" "+word
+ localStorage.setItem("nowWords",currentWords)
+//
+ if(count>0){
+ if(count==1){
+ localStorage.setItem("nowWords",replaceWords(currentWords,word))
+ }else{
+ localStorage.setItem("nowWords",replaceAllWords(currentWords,word,""))
+ }
+ }
+
+
+ pickedWords.value = localStorage.getItem("nowWords")
document.getElementById("article").innerHTML = articleContent;
return;
}