在这里插入图片描述

工具类:

export class TextUtil {
  public static readonly REGEX_B_S = "<B>"
  public static readonly REGEX_B_E = "</B>"
  
  /**
   * 获取高亮字符串列表
   * @param str 原始字符串
   */
  public static getHlList(str ?: string, regex ?: string): HlContent[] {
    if (str == undefined) {
      return []
    }

    let list: HlContent[] = []
    if (regex == undefined || !str.includes(regex)) {
      let content = new HlContent()
      content.content = str
      list.push(content)
      return list
    }

    if (TextUtil.REGEX_B_S == regex) {
      let splitStr: string[] = str.split(regex)
      for (let i = 0; i < splitStr.length; i++) {
        let temp = TextUtil.getHlList(splitStr[i], TextUtil.REGEX_B_E)
        if (temp != null && temp.length > 0) {
          list = list.concat(temp)
        }
      }
    }
    if (TextUtil.REGEX_B_E == regex) {
      let content1 = new HlContent()
      content1.isHl = true
      content1.content = str.substring(0, str.indexOf(regex))
      list.push(content1);

      let startIndex = str.indexOf(regex) + TextUtil.REGEX_B_E.length
      let endIndex = str.length
      if (startIndex < endIndex) {
        let content2 = new HlContent()
        content2.content = str.substring(startIndex, endIndex)
        list.push(content2);
      }
    }
    return list
  }
}

实体类:

export class HlContent {
  content: string = ""
  isHl: boolean = false
}

实际使用中:

let contentStr = '北京大学'
let keyword = '大学'
Text() {
		//因为工具类只是识别b标签,这里先将'北京大学'替换成了'北京<b>大学</b>'
          ForEach(TextUtil.getHlList(contentStr.replace(keyword,
            `${TextUtil.REGEX_B_S}${keyword}${TextUtil.REGEX_B_E}`), TextUtil.REGEX_B_S), (item: HlContent) => {
            if (item != null && item.content != null && item.content.length > 0) {
            //设置“大学”为红色,其他字体为黑色
              if (item.isHl) {
                Span(item.content).fontColor(Color.Red)
              } else {
                Span(item.content).fontColor(Color.Black)
              }
            }
          })
        }.fontSize(14)

原文:https://www.jianshu.com/p/a33f445d1c75 略作改动

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部