The Best Practice To Remove Empty HTML Tag With Regex In JS 2023

By XiaoXin
A Bit Randomly

The core is the kernel of the unix system. When your program has memory out of bounds, the operating system will terminate your process and dump the current memory state to the core file for further analysis. Programmers c... Read Linux: what is the core file and what is its use?

Main Contents
  1. Example Input
  2. The Regex 
  3. Result

The Best Practice To Remove Empty HTML Tag With Regex In JS

How to remove empty HTML tags with any attributes inside that may contain (space, line break,  ) by regular expression in javascript.

Example Input

const string = `<p></p>
<p>  </p>
<b>
   
   </b>	
<B></B>
<i>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</i>
<i>     &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</i>
<i>  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;  </i>
<strong></strong>
<i style="color: orange"></i>
<a href="#">     </a>
<o: class="ms-crap"></o>

<p>Not empty</p>
<p>Not 
   empty</p>
<i> &nbsp;&nbsp;

&nbsp;&nbsp; </i>
`;

The Regex 

let result = string.replace(/<.[^>]*>(\s+|()|(&nbsp;)*|\s+(&nbsp;)*|(&nbsp;)*\s+|\s+(&nbsp;)*\s+)<\/.[^>]*>/ig, '')

Result

result = `
<p>Not empty</p>
<p>Not 
   empty</p>
<i> &nbsp;&nbsp;

&nbsp;&nbsp; </i>
`;

Can you fast to create an example data test online in https://regex101.com/r/NR2mUD/1

Please Share This Article Thank You!

Learn How HTTPS Can Give You A SEO Boost

Using HTTPS (Hypertext Transfer Protocol Secure) can give your website a SEO boost in several ways. HTTPS is a more secure version of HTTP, the protocol used to transfer data on the internet. Google has stated that it may ...

NodeJS Error Handling Simple Practices

Here is an example of using a try-catch block in Node.js: try { // code that may throw an error const result = someFunction(); console.log(result); } catch (error) { // handle the error console.error(error); } In this exam...