40
rated 0 times
[
43]
[
3]
/ answers: 1 / hits: 44606
/ 9 Years ago, mon, december 28, 2015, 12:00:00
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?
Begin with this:
<h1>A</h1>
<h2>B</h2>
<p>Foobar</p>
<h3>C</h3>
Result:
[<h1>A</h1>, <h2>B</h2><p>Foobar</p>, <h3>C</h3>]
What I've tried:
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)/);
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.
More From » regex