【问题标题】:Implement a text highlighting feature in javascript在 javascript 中实现文本突出显示功能
【发布时间】:2019-10-16 08:09:02
【问题描述】:

我的任务是使用 ExpressJS 创建 API,该 API 将管理将在前端制作的亮点。如果有人更新了部分文本,我如何跟踪我突出显示的文本

我保留了突出显示文本的三个开始和结束字符。但问题是,如果文本被编辑,我将如何管理这些字符。

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;

如果部分突出显示的文本被编辑,我将删除我存储中突出显示的部分。如果没有,我想检查我的开始和结束字符是否改变了,然后我相应地改变它们。 但是如果它的索引发生变化,我不知道如何获取突出显示的文本

【问题讨论】:

  • 您可以选择像您一直在做的那样存储开始和结束字符以及字符串中的开始和结束点。然后,当用户更新文本时,您只需根据对文本的编辑移动突出显示的开始和停止位置。因此,如果字符串是The quick brown fox 并且突出显示了quick,则可以存储(4,8),然后如果用户将文本更改为The red quick brown fox,则位置将移动4 到(8,12)。显然,您会根据键输入一次将突出显示的项目移动一个索引
  • 你为什么要匹配三个开始和结束字符而不是整个单词?
  • @MichaelPlatt,我想过这个,但我没有实现它。我将如何捕获突出显示的 tex 的新索引
  • 它可能会有点复杂,但 1000 英尺的视图将是在组件上设置一个更改侦听器,该侦听器可以更改并包含突出显示的单词。当有变化时,您可以检查变化发生的位置,然后相应地增加或减少突出显示的单词的索引。
  • @AkimanaAjoullyJeand'Amour "如果部分突出显示的文本被编辑,我将删除我存储中突出显示的部分。如果没有,我想检查我的开始和结束字符是否发生了变化,然后我相应地更改它们。“重点是我的。如果文本没有被编辑……你为什么要检查它是否改变了?是否暗示突出显示的文本与未突出显示的文本不同?如果是这样,那么您可能会陷入细枝末节。

标签: javascript arrays string sorting split


【解决方案1】:

因此,如果您考虑跟踪突出显示文本之外的编辑,这将不像您想象的那么容易。

  1. 文本可能包含多个相似的短语/单词(突出显示)
  2. 新插入的短语可能与突出显示的短语相似(就索引而言,如果在主要短语之前则更糟)

因此,如果发生上述任何一种情况,索引将毫无用处,因为您可能会陷入错误的文本

执行以下操作

一个。突出显示时保留以下内容 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.

请记住在突出显示的文本无害之后发生的任何编辑。 希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-19
    • 2019-01-20
    • 2012-05-10
    • 2021-05-03
    • 1970-01-01
    • 2013-04-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多