字符串嵌入另一字符串时的高亮显示问题技术咨询
我来帮你搞定这个字符串嵌入高亮的问题!咱们核心目标就是根据给定的起止偏移量JSON,把原文本对应区间的内容用Markdown格式高亮出来,我给你梳理一套落地的步骤和代码示例。
第一步:先明确数据结构
假设你的偏移量JSON是类似这样的格式(如果实际结构不同,后面代码可以微调适配):
[ {"start": 6, "end": 11}, {"start": 92, "end": 103}, {"start": 270, "end": 291} ]
对应的原文本就是你提供的那段Lorem Ipsum内容。
第二步:预处理偏移量(排序+避坑)
首先要把偏移量按start从小到大排序,避免处理顺序混乱;如果遇到重叠的偏移区间,建议先合并(比如两个区间重叠或相邻,就合并成一个大区间),不然高亮会出现嵌套或重复的问题。
第三步:拼接高亮后的文本
我们可以通过遍历原文本,结合偏移区间分段拼接普通文本和高亮文本。这里用JavaScript写个实用的示例函数:
// 你的原文本 const originalText = "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"; // 偏移量JSON数据 const highlightOffsets = [ {"start": 6, "end": 11}, {"start": 92, "end": 103}, {"start": 270, "end": 291} ]; function applyMarkdownHighlight(text, offsets) { // 先按start值排序偏移量,避免顺序混乱 const sortedOffsets = [...offsets].sort((a, b) => a.start - b.start); let resultText = ''; let currentCursor = 0; for (const { start, end } of sortedOffsets) { // 先拼接当前光标到高亮起始位的普通文本 if (start > currentCursor) { resultText += text.slice(currentCursor, start); } // 拼接高亮文本(用Markdown的**加粗**作为高亮样式) resultText += `**${text.slice(start, end)}**`; // 更新光标到高亮结束位 currentCursor = end; } // 拼接最后一段未高亮的文本 if (currentCursor < text.length) { resultText += text.slice(currentCursor); } return resultText; } // 生成最终高亮文本 const finalHighlightedText = applyMarkdownHighlight(originalText, highlightOffsets); console.log(finalHighlightedText);
运行后你会得到类似这样的高亮结果:
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
常见问题处理提示
- 偏移量超出文本长度:可以在函数里加判断,如果
start >= text.length或者end > text.length,直接跳过该偏移量,或者把end修正为文本总长度。 - 重叠偏移区间:可以提前写个小逻辑合并重叠/相邻的区间,比如把
{"start":5,"end":15}和{"start":10,"end":20}合并成{"start":5,"end":20},避免高亮嵌套。 - 偏移顺序混乱:一定要先排序,不然处理出来的文本会逻辑错乱。
如果你的偏移量JSON结构不同,或者用Python等其他语言实现,随时调整代码逻辑就行~
内容的提问来源于stack exchange,提问作者ganesh kaspate

