鸿蒙版本arkts,解析带html标签的文本
·
// 1. 先声明分段类型(之前已定义)
interface BoldTextSegment {
content: string;
isBold: boolean;
id: string;
}
// 2. 解析函数中为match显式声明类型
function parseBoldText(htmlText: string): Array<BoldTextSegment> {
const segments: Array<BoldTextSegment> = [];
const regex = /<\s*b\s*>(.*?)<\s*\/\s*b\s*>/gi;
let lastIndex = 0;
let idCounter = 0;
// 关键修正:显式声明match的类型为RegExpExecArray | null
let match: RegExpExecArray | null;
if (!htmlText || htmlText.trim() === '') {
return [{ content: '', isBold: false, id: 'empty' }];
}
// 循环中使用match(类型明确,无any)
while ((match = regex.exec(htmlText)) !== null) {
if (match.index > lastIndex) {
segments.push({
content: htmlText.substring(lastIndex, match.index),
isBold: false,
id: `normal-${idCounter++}`
});
}
segments.push({
content: match[1] || '', // match[1]是捕获组内容,类型安全
isBold: true,
id: `bold-${idCounter++}`
});
lastIndex = regex.lastIndex;
}
if (lastIndex < htmlText.length) {
segments.push({
content: htmlText.substring(lastIndex),
isBold: false,
id: `normal-${idCounter++}`
});
}
return segments;
}
使用方式
private rawText: string = "they went <b>complaining</b> back down";
// 3. 变量类型也使用声明的接口
private parsedSegments: Array<BoldTextSegment> = parseBoldText(this.rawText);
Text() {
ForEach(
this.parsedSegments,
(segment: BoldTextSegment) => { // 遍历项也指定类型
Span(segment.content)
.fontWeight(segment.isBold ? FontWeight.Bold : FontWeight.Normal)
},
(segment) => segment.id
);
}更多推荐




所有评论(0)