鸿蒙给定字符串中某个字符变色

在鸿蒙Next中,给定一个字符串‘今天真开心’,‘真’字符实现和其他字符不同颜色,源码https://gitee.com/scenario-samples/regular-highlight,感谢博主
在这里插入图片描述

class formatString {
  //定义为解析后的标签内容数组,str是要显示的内容,isAim为是否高亮标志
  char: string = '';
  isAim: boolean = false;
}

@Entry
@Component
struct Index {
  @State formatStr: formatString[] = [];
  /**
   * 主串(待匹配的完整字符串)
   */
  @State mainStrInfo: string = '今天真开心';
  /**
   * 子串(用来匹配的部分)
   */
  @State subStrInfo: string = '真';

  // 转义特殊字符的函数
  escapeRegExp(subStr: string): string {
    return subStr.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  }

  processSource(mainStr: string, subStr: string): formatString[] {
    let result: formatString[] = [];
    if (mainStr.length === 0 || subStr.length === 0) {
      // 如果主串或子串为空,则返回空结果
      return result;
    }

    // 对字串进行转义处理
    const escapedSubStr = this.escapeRegExp(subStr);
    // 构建正则表达式
    const globalMatchRegex = RegExp(escapedSubStr, 'g');
    let indexList: number[] = [];
    let matchResult: RegExpExecArray | null = null;
    // 记录所有匹配位置的索引
    while ((matchResult = globalMatchRegex.exec(mainStr)) !== null) {
      indexList.push(matchResult.index, globalMatchRegex.lastIndex - 1);
    }

    let cache = '';
    for (let index = 0; index < mainStr.length; index++) {
      if (!indexList.includes(index)) {
        cache = cache + mainStr[index];
        if (index === mainStr.length - 1) {
          result.push({ char: cache, isAim: false });
        }
      } else {
        if (cache.length > 0) {
          result.push({ char: cache, isAim: false });
          cache = '';
        }
        result.push({ char: subStr, isAim: true })
        index = index + subStr.length - 1;
      }
    }

    return result;
  }

  build() {
    Column() {
        ForEach(this.processSource(this.mainStrInfo, this.subStrInfo), (item: formatString) => {
          if (item.isAim) {
            Text(item.char)
              .fontSize(20)
              .fontColor(Color.Red) //对目标内容进行高亮处理
          } else {
            Text(item.char)
              .fontSize(20);
          }
        })
    }.width('100%').height('100%')
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值