You can parse HTML in the DOM before displaying it on the page. This provides some benefit, since you do not need to include a tag in Regex. An added benefit is that your paragraph elements can include other attributes, such as class names, data - * information, or inline style; which all would fail your Regex test.
Since this is parsed in the DOM before being added to the body, there is another advantage that you do not need to look for in your Regex, you can just look for spaces \s (or vice versa any characters without spaces).
JQuery
var strText ='a<p> </p>c<p> </p>d<p> aa </p>e', $div = $('<div/>').html(strText), $p = $div.find('p'); var empty_paragraph_count = 0; $p.each(function(){ var $this = $(this); if ( /^\s*$/.test( $this.text() ) ){ empty_paragraph_count++;
Then you can do whatever you want with $div.html(); and empty_paragraph_count , showing how many paragraphs were blank or had only spaces.
Vanilla
If you are looking for a VanillaJS solution, you can use the same approach:
var strText = 'a<p> </p>c<p> </p>d<p> aa </p>e', div = document.createElement('div'), div.innerHTML = strText, p = div.getElementsByTagName('p'); var empty_paragraph_count = 0; for(var i=0, n=p.length; i<n; i++){ if( /^\s*$/.test( p[i].textContent ) ){ empty_paragraph_count++; } }
source share