本文原创发布在华为开发者社区。
介绍
本项目通过RegExp正则匹配实现了高亮关键字功能。
效果预览
使用说明
安装完成后首先输入待匹配字符串,然后输入匹配字符串,可以发现下方显示的待匹配字符串中的匹配字符串高亮显示。
实现思路
使用正则表达式模式对字符串执行搜索。
while ((array = regex1.exec(str)) !== null) { indexList.push(array.index, regex1.lastIndex - 1) }
区分高亮和非高亮区域,返回结果。
for (let index = 0; index < str.length; index++) { if (!indexList.includes(index)) { cache = cache + str[index] if (index > indexList[indexList.length-1] && index === str.length - 1) { result.push({ char: cache, isAim: false }) } } else { result.push({ char: cache, isAim: false }) result.push({ char: msg, isAim: true }) index = index + msg.length - 1 cache = '' } }
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。