javascript - 如何获取突出显示的单词的索引?
问题描述
我需要帮助从句子中找到突出显示的单词索引。考虑这句话,我需要突出显示第二条国际新闻,并获取这些单词的索引(索引是句子中单词的开头和结尾,例如 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] 这是单词的第一次出现。我怎样才能得到第二个?
解决方案
推荐阅读
- javascript - 谁能告诉我为什么我的 if/else 语句在 EJS 中不起作用?
- python - 加载工作簿时这个openpyxl“ValueError”是什么意思?
- wordpress - 我们可以根据另一个分类术语获取分类术语列表吗?
- python - Django - Django 标记库包的建议
- python - 加入两个数据框pyspark
- python - 如何从 Python 中的 2D 离散小波变换系数计算香农熵、能量、平均值等?
- google-chrome - 如何使在命令提示符窗口中运行的批处理代码无法关闭?
- msbuild - 如何使用目标标签在 .Net Standard 项目中包含 EmbeddedResource?
- javascript - 在pdf中单击时,有没有办法删除我的默认文本字段值?
- r - 是否有任何函数可以计算 glmer 的部分响应?