本文原创发布在华为开发者社区

介绍

本项目通过RegExp正则匹配实现了高亮关键字功能。

实现高亮关键字源码链接

效果预览

请添加链接描述

使用说明

安装完成后首先输入待匹配字符串,然后输入匹配字符串,可以发现下方显示的待匹配字符串中的匹配字符串高亮显示。

实现思路

  1. 使用正则表达式模式对字符串执行搜索。

    while ((array = regex1.exec(str)) !== null) {
      indexList.push(array.index, regex1.lastIndex - 1)
    }
  2. 区分高亮和非高亮区域,返回结果。

    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 = ''
      }
    }

鸿蒙场景化代码
1 声望0 粉丝