React Native中提取HTML字符串所有<b>标签内文本的方法
解决方案
方法一:正则表达式(适合简单场景)
直接用正则匹配所有<b>与</b>之间的文本,代码如下:
const htmlString = '<div style="margin-left: 10px">I have three dogs. One is called <b>Tiger</b>, the second is called <b>Lion</b>, and the third is called <b>Panda</b>.</div>'; const boldRegex = /<b>([\s\S]*?)<\/b>/g; const result = []; let match; // 循环匹配所有符合条件的内容 while ((match = boldRegex.exec(htmlString)) !== null) { result.push(match[1]); } console.log(result); // 输出: ["Tiger", "Lion", "Panda"]
注意:这个正则是非贪婪匹配,如果遇到<b>外层<b>内层</b></b>这种嵌套标签,会提取到外层<b>内层,若需处理嵌套场景,更推荐下面的库方案。
方法二:使用HTML解析库(适合复杂嵌套场景)
React Native环境可使用纯JS的HTML解析库htmlparser2,它不依赖DOM,能可靠处理嵌套标签、实体编码等复杂情况。
步骤1:安装依赖
npm install htmlparser2 # 或用yarn yarn add htmlparser2
步骤2:编写解析代码
import { Parser } from 'htmlparser2'; // ESModule 导入方式,CommonJS用require const htmlString = '<div style="margin-left: 10px">I have three dogs. One is called <b>Tiger</b>, the second is called <b>Lion</b>, and the third is called <b>Panda</b>.</div>'; const boldTexts = []; let isInBoldTag = false; let currentBoldText = ''; const parser = new Parser({ // 遇到开标签时触发 onopentag(tagName) { if (tagName === 'b') { isInBoldTag = true; currentBoldText = ''; } }, // 遇到文本内容时触发 ontext(text) { if (isInBoldTag) { currentBoldText += text; } }, // 遇到闭标签时触发 onclosetag(tagName) { if (tagName === 'b') { isInBoldTag = false; boldTexts.push(currentBoldText.trim()); } } }, { decodeEntities: true }); // 自动解码HTML实体,比如"转为" // 传入HTML字符串开始解析 parser.write(htmlString); parser.end(); console.log(boldTexts); // 输出: ["Tiger", "Lion", "Panda"]
这个方案能正确处理嵌套的<b>标签,比如<b>Hello <b>World</b>!</b>会提取到Hello World!,稳定性更强。
内容的提问来源于stack exchange,提问作者paperskyline
相关产品推荐
相关产品推荐

