[英]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.