Search code examples
javascripthtmlreplacedomparser

Remove extra elements from html template string


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>
`

Solution

  • 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);