通过特定标记将HTML字符串拆分为数组 [英] Split a string of HTML into an array by particular tags
问题描述
将此HTML作为字符串html,如何将其拆分为一个数组,其中每个标题< h
标记元素的开头?
Given this HTML as a string "html", how can I split it into an array where each header <h
marks the start of an element?
从此开始:
<h1>A</h1>
<h2>B</h2>
<p>Foobar</p>
<h3>C</h3>
结果:
["<h1>A</h1>", "<h2>B</h2><p>Foobar</p>", "<h3>C</h3>"]
我尝试了什么:
我想用正则表达式使用 Array.split()
,但结果会分割每个< h
进入自己的元素。我需要弄清楚如何从一个< h
的开头捕获,直到下一个< h
。然后包括第一个但排除第二个。
I wanted to use Array.split()
with a regex, but the result splits each <h
into its own element. I need to figure out how to capture from the start of one <h
until the next <h
. Then include the first one but exclude the second one.
var html = '<h1>A</h1><h2>B</h2><p>Foobar</p><h3>C</h3>';
var foo = html.split(/(<h)/);
编辑:无论如何都不要求正则表达式,它只是唯一的要求我认为通常以这种方式拆分HTML字符串的解决方案。
Edit: Regex is not a requirement in anyway, it's just the only solution that I thought would work for generally splitting HTML strings in this way.
推荐答案
在您的示例中,您可以使用:
In your example you can use:
/
<h // Match literal <h
(.) // Match any character and save in a group
> // Match literal <
.*? // Match any character zero or more times, non greedy
<\/h // Match literal </h
\1 // Match what previous grouped in (.)
> // Match literal >
/g
var str = '<h1>A</h1><h2>B</h2><p>Foobar</p><h3>C</h3>'
str.match(/<h(.)>.*?<\/h\1>/g); // ["<h1>A</h1>", "<h2>B</h2>", "<h3>C</h3>"]
但请不要使用regexp解析HTML,请阅读 RegEx匹配除XHTML自包含标签之外的开放标签
But please don't parse HTML with regexp, read RegEx match open tags except XHTML self-contained tags
这篇关于通过特定标记将HTML字符串拆分为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!