我在搜索长文本中的字符串时遇到了一些问题.我只想提取搜索的文本和粗体搜索的文本可能有10-20个字符之前和之后的搜索字符.

所以基本上我想要实现的是,例如.从那篇文章中可以看出:

你好,我想实现一个新的目标,为其创建一个良好的搜索栏 我的应用程序.它应该和任何其他搜索栏一样.

因此,如果我想搜索"Good Search",它应该返回如下内容:

...实现一个新目标,为我的应用程序创建good search个栏.它 应该只是...

做这件事最好的办法是什么?我try 了一些类似的方法:

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;
// To determine where is the first character
const find_first = text.search(search_text)
const search_from = find_first - radius;
    
// To ensure that we are taking from first with length of searched text and additional ones
const search_to = find_first + search_text.length + radius

但是,这仅仅是为了确定如何判断要获取哪些字符.但如何列出它们并突出显示呢?

推荐答案

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 = 20;

const indexPosition = text.search(search_text)
const startPosition = indexPosition - RADIUS 
const endPosition = indexPosition + RADIUS + search_text.length
const searchResult = (`...${text.slice(startPosition, endPosition)}...`).replace(search_text, `<b>${search_text}</b>`)
console.log({searchResult})
  

然后你可以用你喜欢的方式应用你的高亮显示,(我在搜索文本周围添加了<b>个标签,我想你想要它为HTML格式)

Javascript相关问答推荐

如何在表格上拥有水平滚动条,在正文页面上拥有垂直滚动条,同时还对html表格的标题使用位置粘性?

Vue:ref不会创建react 性属性

如何分配类型脚本中具有不同/额外参数的函数类型

没有输出到带有chrome.Devtools扩展的控制台

在页面上滚动 timeshift 动垂直滚动条

通过嵌套模型对象进行Mongoose搜索

如何在JavaScript文件中使用Json文件

在执行异步导入之前判断模块是否已导入()

当使用';字母而不是与';var#39;一起使用时,访问窗口为什么返回未定义的?

正则表达式,允许我匹配除已定义的子字符串之外的所有内容

JQuery Click事件不适用于动态创建的按钮

用JS从平面文件构建树形 struct 的JSON

有条件重定向到移动子域

如何在箭头函数中引入or子句?

将异步回调转换为异步生成器模式

将对象推送到数组会导致复制

无法读取未定义的属性(正在读取合并)-react RTK

递增/递减按钮React.js/Redux

观察子组件中的@Output事件emits 器?

带有JS模块模式的Rails的Importmap错误:";Net::ERR_ABORTED 404(未找到)&Quot;