可以参考此文档:https://docs.openharmony.cn/pages/v4.0/zh-cn/application-dev/ui/arkts-common-components-text-display.md/使用span来高亮展示你所需要的文字。class formatS { //定义为解析后的标签内容数组,str是要显示的内容,isAim为是否高亮标志 char: string = ""; isAim: boolean = false; } @Entry @Component struct Index { @State sourceStr: string = '几点睡啊你好吗几点睡啊你好吗你好吗几点睡啊你好吗你好吗几几点睡啊点'; @State formatStr: formatS[] = [] processSource(str: string): formatS[] { let result: formatS[] = [] const regex1 = RegExp('几点睡啊', 'g'); let indexList: number[] = [] let array: RegExpExecArray | null = null while ((array = regex1.exec(str)) !== null) { console.log(`start: ${array.index},Found ${array[0]}.end ${regex1.lastIndex - 1}.`); indexList.push(array.index, regex1.lastIndex - 1) } let cache = "" 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: "几点睡啊", isAim: true }) index = index + "几点睡啊".length - 1 cache = "" } } return result } build() { Column() { ForEach(this.processSource(this.sourceStr), (item: formatS) => { if (item.isAim) { Text(item.char).fontSize(20).fontColor(Color.Red); //对目标内容进行高亮处理 } else { Text(item.char).fontSize(20); } }) }.width('100%').height('100%') } }
可以参考此文档:
https://docs.openharmony.cn/pages/v4.0/zh-cn/application-dev/ui/arkts-common-components-text-display.md/
使用span来高亮展示你所需要的文字。