-1

I have some text:

<p>I hope that this works!</p> <p>Now that this is in, let's see!</p><p>I hope that bold <strong>works too</strong>!</p>
<p>Will this works</p><ol><li>First item</li><li>Second item</li><li>Third item</li></ol>

I want to split it into:

<p>I hope that this works!</p>

and

<p>Now that this is in, let's see!</p><p>I hope that bold <strong>works too</strong>!</p>

and

<ol><li>First item</li><li>Second item</li><li>Third item</li></ol>

I don't want to split on any of the child elements, just the siblings?

Shamoon
  • 41,293
  • 91
  • 306
  • 570

1 Answers1

2

The preferred way to parse an X/HTML-alike string is by using the DOMParser API

const str = `<p>I hope that this works!</p>
  <p>Now that this is in, let's see!</p>
  <p>I hope that bold <strong>works too</strong>!</p>
  <p>Will this works</p>
  <ol><li>First item</li><li>Second item</li><li>Third item</li></ol>`;

const doc = new DOMParser().parseFromString(str, "text/html");

console.log(doc.body.children)

Or like this, to map the outerHTML as an Array of strings

const str = `<p>I hope that this works!</p>
  <p>Now that this is in, let's see!</p>
  <p>I hope that bold <strong>works too</strong>!</p>
  <p>Will this works</p>
  <ol><li>First item</li><li>Second item</li><li>Third item</li></ol>`;

const doc = new DOMParser().parseFromString(str, "text/html");
const children = doc.body.children;
const chStrArr = [...children].map(el => el.outerHTML);

console.log(chStrArr);
Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
  • Is `DOMParser` fast? – Shamoon Jul 03 '20 at 01:28
  • 1
    @Shamoon If you find browsers fast in interpreting and creating a [DOM](https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model), than yes. It's the first best thing you can use - not only for that specific task, but whenever you need to parse strings as actual Documents (which is by no means a RegExp job). – Roko C. Buljan Jul 06 '20 at 17:18