我是angular js
的新手。在这里,我有一个字符串
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged
现在,我在这里试图突出显示文档中的文本现在,问题就像 - >
在本文中,我强调Lorem Ipsum已经添加了一些span类。现在,对于下一次交互,如果startoffset和endoffset有一个字符串,但是Ipsum已经成为业界的标准。现在,这两个将重叠,然后突出显示重叠。所以,我无法得到确切的文本,因为偏移量会发生变化。
现在,为此,我尝试了以下解决方案 - >
const str = 'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry\'s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged';
const highlights = [{startOffset: 2, endOffset: 16}, {startOffset: 68, endOffset: 75}, {startOffset: 80, endOffset: 92}];
const result = [];
let currentIndex = 0;
highlights.forEach(h => {
result.push(str.substring(currentIndex, h.startOffset));
result.push(`<span class="mark">${str.substring(h.startOffset, h.endOffset)}</span>`);
currentIndex = h.endOffset;
});
result.push(str.substring(currentIndex, str.length));
document.getElementById('root').innerHTML = result.join('')
现在,在这里,它解决了我的问题,但是如果它重叠,那么我的字符串中会添加一个重复的文本。如果有一个文本相互重叠,那么它就是分开文本。但我不想要那种行为。任何人都可以帮助我吗?
答案 0 :(得分:0)
我不确定,如果我理解你的问题,但你的问题发生了,如果突出显示的区域重叠,就像这样?
var highlights = [{startOffset: 2, endOffset: 16},
{startOffset: 85, endOffset: 100},
{startOffset: 80, endOffset: 92}];
要实现这一目标,您必须首先制作不同的区域。
highlights.sort(function (a, b) {return a.startOffset - b.startOffset; }); //first order by the start offset
// highlights looks like this
//[{startOffset: 2, endOffset: 16},
// {startOffset: 80, endOffset: 92},
// {startOffset: 85, endOffset: 100}]
// next merge all overlapping areas
for(var i = 0; i < highlights.length - 1; i++) { //each element but the last, because it can't overlap with the next
if(highlights[i].endOffset > highlights[i + 1].startOffset) { //if it overlaps with the next
highlights[i].endOffset = highlights[i].endOffset > highlights[i + 1].endOffset ?
highlights[i].endOffset : highlights[i + 1].endOffset; //take the higher end offset of those two as new offset
highlights.splice(i + 1, 1); //remove next element in list, since it is no longer useful
i--; //check current element again
}
}
//output
//[{startOffset: 2, endOffset: 16},
// {startOffset: 80, endOffset: 100}]
之后,您的代码应该有效。