简体   繁体   English

Javascript HTML 字符串转换成标签数组和内部内容

[英]Javascript HTML string into array of tags and inner content

I am trying to match on HTML tags and their inner content and put each match into an array (both the tag and its inner contents).我正在尝试匹配 HTML 标签及其内部内容,并将每个匹配项放入一个数组(标签及其内部内容)。

I was able to match the tags themself and put those into an array, but I'm not sure how to get the inner contents of the tag as well.我能够自己匹配标签并将它们放入一个数组中,但我也不确定如何获取标签的内部内容。

// Example String
let str = "<p><b>Label:</b>Value<p></p><p><b>New Line Label:</b>Value 2</p></p>";
console.log(str.match(/\<.*?\>/gi)) // Output ["<p>", "<b>", "</b>", "<p>", "</p>", "<p>", "<b>", "</b>", "</p>", "</p>"]


// Expected Output
["<p>", "<b>", "Label:", "</b>", "Value", "<p>", "</p>", "<p>", "<b>", "New Line Label:", "</b>", "Value 2", "</p>", "</p>"]

Can this be handled in a single regex match, or do I need to match and then look back to the closing previous tag to get the inner content?这可以在单个正则表达式匹配中处理,还是我需要匹配然后回头查看关闭的前一个标签以获取内部内容?

You could use DOMParser API and then keep iterating through childrens of each node您可以使用 DOMParser API ,然后继续遍历每个节点的子节点

let doc = new DOMParser().parseFromString('<p><b>Label:</b>Value<p></p><p><b>New Line Label:</b>Value 2</p></p>', 'text/html')

console.log(doc.children) // DOM nodes 

with this you'll have constructed a complete DOM from string you have then apply any function you'd like on it有了这个,你就可以从字符串构造一个完整的 DOM,然后应用你想要的任何 function

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 删除没有内部内容Javascript的内部html标签 - Remove inner html tags without inner content Javascript 使用 JavaScript,如何将 HTML 字符串转换为 HTML 标签和文本内容的数组? - Using JavaScript, how do I transform an HTML string into an array of HTML tags and text content? 循环遍历字符串中的html标记并将内部文本添加到数组中 - loop through html tags in string and add inner text to array 用Javascript抓取内部html标签 - Grabbing inner html tags with Javascript 显示 HTML 标签内部 html 标签中的字符串 - Display HTML tags a string in inner html tag 用空格分隔字符串(包含标签),而不会破坏标签或Javascript中的标签内部html - Split a string (that contains tags) by spaces without breaking the tags or tag inner html in Javascript 如何使用javascript或angularjs从字符串中提取html标签的内容? - How to extract content of html tags from a string using javascript or angularjs? 使用Javascript从HTML字符串的标签中获取内容 - Get content from tags in HTML-string with Javascript 如何删除仅带有特定类名且不包含字符串内部内容的html标签(跨度)? - How to remove html tags (span) wrap only with specific class name and without inner content from a string? 将html标签和内容转换为字符串 - converting html tags and the content to string
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM