Home > database >  Changing wrapping tags and keeping content inside tags with regex
Changing wrapping tags and keeping content inside tags with regex

Time:10-21

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 >(.*?)<\/p>/, '<ul><li>$1</li>');
html = html.replace(/<p >(.*?)<\/p>/, '<li>$1</li>');
html = html.replace(/<p >(.*?)<\/p>/, '<li>$1</li><ul>');

Current mark up below

<p >Item 1</p>
<p >Item 2</p>
<p >Item 3</p>

Desired mark up below

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

CodePudding user response:

You are missing the slash / in theul closing tag.

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

document.body.innerHTML = html;
<p >Item 1</p>
<p >Item 2</p>
<p >Item 3</p>

  • Related