首页 > 解决方案 > 如何拆分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"]
[

标签: javascripthtmlreactjs

解决方案


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}));

推荐阅读