1

I have an html template and I want to remove the extra <p></p> from it via JS.
P.S. I cannot have more than one empty p.

Example:

const htmlTemplate = `
  <p>Rich editor text</p>
  <p></p>
  <p></p> // <-- Remove these extra elements
  <p>1.2.3</p>
  <p>test432</p>
  <p></p>
  <p></p> // <--
  <p>lorem</p>
  <p></p>
  <p></p>  // <--
  <p></p>  // <--
  <p>ipsum dolor amet</p>
`

Result:

const result = `
  <p>Rich editor text</p>
  <p></p>
  <p>1.2.3<br></p>
  <p>test432</p>
  <p></p>
  <p>lorem</p>
  <p></p>
  <p>ipsum dolor amet</p>
`
  • What have you tried so far ? – ajobi 2 days ago
  • Why are there empty <p></p> in the output? You do not want more than one empty p consecutively? – adiga 2 days ago
  • From the result, I can see two more <p></p> those I are not extra? – Nicolae Maties 2 days ago
  • @NicolaeMaties, you're right – Arthur 2 days ago
  • 1
    You can use DOMParser to convert the string to a document object and then loop through children elements – adiga 2 days ago
3

You can use a regex to search and remove unwanted <p></p>. You can use https://regex101.com/ to get the details of the regex

const htmlTemplate = `
  <p>Rich editor text</p>
  <p></p>
  <p></p>
  <p>1.2.3</p>
  <p>test432</p>
  <p></p>
  <p></p>
  <p>lorem</p>
  <p></p>
  <p></p>
  <p></p> 
  <p>ipsum dolor amet</p>`;

const ret = htmlTemplate.replace(/<p><\/p>([.\s]*<p><\/p>)+/ig, '<p></p>');

console.log(ret);

  • 1
    Great answer! I also think {1,} can be replaced with + in you regexp. – Arthur 2 days ago
  • 1
    @Arthur correct :) I changed it – Grégory NEUT 2 days ago

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.