首页 > 解决方案 > 如何获取突出显示的单词的索引?

问题描述

我需要帮助从句子中找到突出显示的单词索引。考虑这句话,我需要突出显示第二条国际新闻,并获取这些单词的索引(索引是句子中单词的开头和结尾,例如 Barack Obama 是 0 和 1,Donald Trump 是 8 和 9)

巴拉克 奥巴马 周三 似乎 对 唐纳德 特朗普 进行 了 抨击 , 说 他 会 “ 建议 , 如果 你 是 总统 ” 避免 国际 新闻 . 这位美国前总统作为嘉宾在国际新闻和软件公司 Splunk 的一次活动中发言,当时他被问及在任期间如何解析信息。

我最好的尝试是:

function getTextSelection() {
  let selection = '';
  // get the higlighted text string
  if (window.getSelection) {
      selection = window.getSelection().toString();
  } else if (document.selection && document.selection.type != "Control") {
      selection = document.selection.createRange().text;
  }

  const wordLength = selection.split(' ').length;
  // theSentence is the full sentence split to array of word
  const initial = theSentence.indexOf(selection.split(' ')[0]);
  return [initial, initial + wordLength - 1];
},

使用该代码,如果我突出显示第二个国际新闻,它将返回 [27, 28] 这是单词的第一次出现。我怎样才能得到第二个?

标签: javascriptvue.js

解决方案


推荐阅读