首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何拆分html字符串并获得带有值的不同标记

如何拆分html字符串并获得带有值的不同标记
EN

Stack Overflow用户
提问于 2020-01-09 15:02:07
回答 7查看 280关注 0票数 0

所以我有很多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>

现在我想把数据作为

代码语言:javascript
复制
[
  ["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"]
[
EN

回答 7

Stack Overflow用户

回答已采纳

发布于 2020-01-09 15:27:17

您可以创建一个虚拟DOM元素:

代码语言:javascript
复制
const dummy = document.createElement("div"); 

将字符串追加为innerHTML:

代码语言:javascript
复制
dummy.innerHTML = 'YOUR_STRING';

然后你可以像这样遍历/映射它的孩子:

代码语言:javascript
复制
const mappedChildren = Array.from(dummy.children).map(child => ({ tag: child.tagName, text: child.innerHTML}));
票数 3
EN

Stack Overflow用户

发布于 2020-01-09 15:32:49

代码语言:javascript
复制
const input = '<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>\n'

const parse = (s) => {
  const regex = /<(.+?)>(.+?)<\/.+?>/g;
  let match = regex.exec(s);
  const result = []
  while (match != null) {
    result.push([match[1], match[2]])
    match = regex.exec(s);
  }
  return result
}

console.log(parse(input))

regex将捕获带有内容的标记,捕获组将分别捕获tagstag名称和内容。

票数 1
EN

Stack Overflow用户

发布于 2020-01-09 15:28:42

您可以使用

代码语言:javascript
复制
var element = document.createElement('div');
element.innerHTML = 'your string...';
var result = [].slice.call(element.children).map(c => ([c.tagName.toLowerCase(), c.innerText]))
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59666763

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档