I am currently working on a project that involves removing multiple empty paragraphs using jQuery and regex within a contenteditable div. However, I have encountered an issue that I need help with. To see an example of what I'm trying to accomplish, you can check out this DEMO.
In the demo, if you hit enter, the JavaScript code doesn't allow the creation of a new paragraph. Instead, I want it to remove any instances where the user creates three consecutive empty paragraphs.
Here is what I do not want to allow:
Hi
Bro
How are you
thanks
My desired outcome should look like this:
Hi
Bro
How are you
thanks
Below are snippets of my code:
$(document).ready(function() {
$("body").on("keyup", ".text", function() {
var item = document.getElementsByClassName("text")[0];
var text = item.innerText || item.textContent;
text = text.replace(/<[\/]{0,1}(p)[^><]*>/gi, ' ');
document.getElementsByClassName("text")[0].innerHTML = text;
});
});
.text {
position:relative;
width:100%;
max-width:500px;
margin:0px auto;
padding:30px;
border:1px solid #d8dbdf;
margin-top:50px;
border-radius:3px;
-webkit-border-radius:3px;
-moz-border-radius:3px;
}
.text[contentEditable=true]:empty:not(:focus):before {
content:attr(placeholder);
color: #444;
}
* {
box-sizing:border-box;
-webkit-box-sizing:border-box;
-moz-box-sizing:border-box;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="text" contenteditable="true" placeholder="Write something with tree times enter"></div>