Erasersharp
Erasersharp

Reputation: 368

Changing wrapping tags and keeping content inside tags with regex

Using regex I am trying to change these p tags be wrapped in a ul tag and converted to li items. I have the below regex to target the specific class and grab whatever content is inside the p tag. But it doesnt look to playing ball. Any direction would be great.

html = html.replace(/<p class="MsoListParagraphCxSpFirst">(.*?)<\/p>/, '<ul><li>$1</li>');
html = html.replace(/<p class="MsoListParagraphCxSpMiddle">(.*?)<\/p>/, '<li>$1</li>');
html = html.replace(/<p class="MsoListParagraphCxSpLast">(.*?)<\/p>/, '<li>$1</li><ul>');

Current mark up below

<p class="MsoListParagraphCxSpFirst">Item 1</p>
<p class="MsoListParagraphCxSpMiddle">Item 2</p>
<p class="MsoListParagraphCxSpLast">Item 3</p>

Desired mark up below

<ul>
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
</ul>

Upvotes: 0

Views: 87

Answers (1)

Mina
Mina

Reputation: 17099

You are missing the slash / in theul closing tag.

let html = document.body.innerHTML;
html = html.replace(/<p class="MsoListParagraphCxSpFirst">(.*?)<\/p>/, '<ul><li>$1</li>');
html = html.replace(/<p class="MsoListParagraphCxSpMiddle">(.*?)<\/p>/, '<li>$1</li>');
html = html.replace(/<p class="MsoListParagraphCxSpLast">(.*?)<\/p>/, '<li>$1</li></ul>');

document.body.innerHTML = html;
<p class="MsoListParagraphCxSpFirst">Item 1</p>
<p class="MsoListParagraphCxSpMiddle">Item 2</p>
<p class="MsoListParagraphCxSpLast">Item 3</p>

Upvotes: 3

Related Questions