简体   繁体   English

在javascript中实现文本突出显示功能

[英]Implement a text highlighting feature in javascript

I have a task to create API using ExpressJS that will manage highlights which will be made on the frontend. 我有一个任务是使用ExpressJS创建API,它将管理将在前端进行的突出显示。 How can I keep track of my highlighted text if someone updates a part of the text? 如果有人更新了部分文本如何跟踪突出显示的文本?

I was keeping the three starting and ending characters of the highlighted text. 我保留了突出显示文本的三个开头和结尾字符。 But a problem is, how will I manage those characters if the text is edited. 但问题是,如果编辑文本,我将如何管理这些字符。

const { textH, allText } = req.body;
let chars = { };
const enclosingChars = (hLighted, theString) => {
  let startingChars = null, endingChars = null;
  const index = theString.indexOf(hLighted);
  const last3 = index + hLighted.length;
  if ((index - 3) > -1) startingChars = theString.substring(index - 3, index);
  if ((index + 3) <= theString.length) endingChars = theString.substring(last3, last3 + 3);
  return { startingChars, endingChars };
};
if (allText.includes(textH)) {
  chars = enclosingChars(textH, allText);
}
chars.hLighted = textH;

If a part of the highlighted text is edited, I will delete the highlighted in my storage. 如果编辑了突出显示文本的一部分,我将删除存储中突出显示的内容。 If not, I want to check if my starting and ending characters have changed, then I change them accordingly. 如果没有,我想检查我的开始和结束字符是否已经改变,然后我相应地更改它们。 But I don't know how to get that highlighted text if its index changed 但我不知道如果其索引发生变化,如何获得突出显示的文本

so it will be not as easy as you think if you consider keeping track of edits outside of the highlighted text. 因此,如果您考虑在突出显​​示的文本之外跟踪编辑,那么就不会像您想象的那么容易。

  1. the text might contain more than one similar phrase/word (to the highlighted) 文本可能包含多个相似的短语/单词(突出显示)
  2. the newly inserted phrase might be similar to the highlighted one (worse if before the main one in terms of indices) 新插入的短语可能类似于突出显示的短语(如果在索引方面,则更差,如果在主要短语之前)

so if any of the above scenarios happens the indices will be of no use because you can fall to the wrong text 因此,如果出现上述任何情况,索引将无用,因为您可能会出现错误的文本

Do the following 请执行下列操作

a. 一种。 when highlighting keep the following 1. the content : to make sure if the edit happens in there, you know it and you can act accordingly 当突出显示时保留以下内容1.确保编辑是否发生在那里,你知道它,你可以采取相应的行动

   2. keep track of the index range of your text even in case the shift is required (when the text before it is edited)

   3. take a screenshot of the entire article and store it so that when an edit to the article happens you know exactly which part is edited. this will require to check word by word and see if any word in the new text is different from the word of the same index in the old (screenshot). and you can shift the ranges of the highlighted text accordingly.

Remember any edit that happens after the highlighted text is innocuous. 请记住突出显示的文本无害后发生的任何编辑。 Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM