You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript实现字符串搜索高亮及上下文截取的技术问题

长文本搜索片段提取与高亮实现

针对你已计算好截取范围的基础上,补充完整的片段提取和高亮逻辑,以下是可直接运行的JavaScript实现:

const text = "Hi there, I want to achieve a new goal to create a good search bar for my app. It should be just as any other search bar."
const search_text = "good search"
const radius = 10;

// 定位搜索文本的起始索引
const find_first = text.search(search_text);
// 处理未找到搜索内容的情况
if (find_first === -1) {
  console.log("未匹配到目标内容");
}

// 修正截取范围,避免超出文本边界
const search_from = Math.max(0, find_first - radius);
const search_to = Math.min(text.length, find_first + search_text.length + radius);

// 截取目标上下文片段
let snippet = text.slice(search_from, search_to);

// 对搜索文本进行高亮处理
snippet = snippet.replace(search_text, `<strong>${search_text}</strong>`);

// 根据截取位置添加省略号,优化上下文展示
if (search_from > 0) {
  snippet = `...${snippet}`;
}
if (search_to < text.length) {
  snippet = `${snippet}...`;
}

console.log(snippet);
// 输出:...ate a <strong>good search</strong> bar for my...

关键逻辑说明

  • 边界修正:通过Math.max和Math.min确保截取起始位置不会小于0,结束位置不会超过文本总长度,避免无效截取
  • 片段截取:使用slice()方法精准获取指定范围的文本片段
  • 高亮替换:利用字符串replace()方法将目标搜索文本替换为带<strong>标签的高亮内容
  • 省略号优化:判断截取片段是否处于文本首尾,添加对应省略号,让上下文展示更直观

内容的提问来源于stack exchange,提问作者Rade Iliev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 09:11:31