javascript - 如何拆分html字符串并获得不同的标签值
问题描述
所以我有很多 html 字符串,我想拆分并获取适当的 html 标签。
让字符串成为<h2>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum</h2> <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum</p> <h6>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum</h6> <h3>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum</h3>
现在我想数据为
[
["h2","Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum"],
["p","Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum"],
["h6","Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum"],
["h3","Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum"]
[
解决方案
You can create a dummy DOM element:
const dummy = document.createElement("div");
Append your string to it as innerHTML:
dummy.innerHTML = 'YOUR_STRING';
And then you can traverse/map its children like so:
const mappedChildren = Array.from(dummy.children).map(child => ({ tag: child.tagName, text: child.innerHTML}));
推荐阅读
- node.js - 从 Node.js 中的另一个方法调用一个方法
- python - 试图从 python 应用程序获取 JSON 数据到谷歌表
- html - 如何使 div 内的图像与另一个 div 重叠?
- javascript - 如何使用 localStorage 将商品保存到购物车
- c++ - c ++如何从文件加载异构集合
- ios - 如何快速访问从 GameScene 到 ViewController 的整数变量
- python - 将字符转换为葡萄牙语特殊字符
- sql - 无法从 Mysql blob 列获取图像
- python - Python 解释器是否检查缩进是空格还是制表符?
- php - 来自两个表的 Firebase 数据查询