WordPress NBSP visual/text bug
Demonstrates a bug in WordPress and shows a fix.
by Brian Layman
HTML
<h1>
Original sample text with no regex run on it.
</h1>
<div id="sample">
<h2>1. An example of 2 correctly empty paragraph tags that should remain</h2>
Desired result: Two blank lines before the hr<br/>
<p> </p>
<p> </p>
<hr/>
<h2>2. An example of a non-empty paragraph buried in another paragraph that incorrectly causes a <p>&nbsp;<p> to be added (view source to see it). </h2>
Desired result: Zero blank lines before the hr<br/>
Expected Error result: One blank lines before the hr<br/>
<p><span style="text-decoration: underline;"><p>[gift id="61513" ]</p></span></p>
<hr/>
<h2>3. An example simulating switching between visual and text being done a second time. This there are two sets of <p>&nbsp;<p> added.</h2>
Desired result: One blank lines before the hr<br/>
Expected Error result: Two blank lines before the hr<br/>
<p><span style="text-decoration: underline;"><p>[gift id="61513" ]</p></span></p><p> </p>
<hr/>
</div>
<h1>
WordPress's current code executed when switching between visual and text
</h1>
<div id="existingregex">
existingregex
</div>
<h1>
A simple fix dropping the *
</h1>
<div id="fixedregex">
fixedregex
</div>
JavaScript
var str = document.getElementById('sample').innerHTML;
document.getElementById('existingregex').innerHTML = str.replace(/<p>(?:<br ?\/>|\u00a0|\uFEFF| )*<\/p>/g, "<p> </p>");
document.getElementById('fixedregex').innerHTML = str.replace(/<p>(?:<br ?\/>|\u00a0|\uFEFF| )<\/p>/g, "<p> </p>");