Using regex in a contenteditable div, JQuery can remove multiple instances of <p> tags simultaneously

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>

Answer №1

p:empty + p:empty + p:empty { display: none; }

It seems like the solution provided above might not work as intended, especially if your paragraphs are not truly empty and contain line breaks (<br />). In this case, you can consider using a JavaScript function to identify and remove the third empty paragraph:

function removeThirdParagraph() {
  let clone = $('.text').clone();
  clone.html($('.text')[0].innerHTML);
  let ps = clone.find('p');
  
  ps.each(function(i,e){
    if ($(e).is('p + p + p') 
    && isEmptyP(ps.eq(i - 2)) 
    && isEmptyP(ps.eq(i - 1))
    && isEmptyP(ps.eq(i))) {
      e.remove();
    }
  });
  // You may want to update the original HTML with the modified content
  $('.text').html(clone[0].innerHTML)
}
function isEmptyP(p){
  return p.text().replace(/(?:\r\n|\r|\n|\s)/g, '').length == 0;
}
removeThirdParagraph();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="text">
  <p>
    <br />
  </p>
  <p>
    <br />
  </p>
  <p>
    <br />
  </p>
  <p>
    <br />
  </p>
  <p>
    test
  </p>
  <p>
    <br />
  </p>
  <p>
    <br />
  </p>
  <p>
    <br />
    <br />
    <br />
    <br />
  </p>
  <p>another test</p>
  <p>
    <br />
  </p>
  <p></p>
  <p></p>
  <p></p>
  
  <p></p>
  <p></p>
  <p></p>
  <p></p>
  <p>...</p>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The spacing issue in jQuery autocomplete is causing the results to not display properly within the modal

My webpage serves as a basic school student/class manager. Currently, I have two search bars that trigger different API calls, both returning a List. However, the issue arises when displaying the results as they have spaces between them. Another problem I ...

When a function is transferred from a parent component to a child component's Input() property, losing context is a common issue

I have encountered an issue while passing a function from the parent component to the child component's Input() property. The problem arises when the parent's function is called within the child component, causing the this keyword to refer to th ...

Issues arise when there is excessive tapping on an iPad while incorporating jQuery animate and scrollTop() commands

I am currently in the process of designing a user interface for a web application. The layout I have in mind is similar to what can be found here. $("#scroll-down").on("click", function() { thumbnails.stop(true, true).animate({ scrollTop: &apos ...

How can PHP information be transmitted to an Ajax response?

I stumbled upon this script online that I'm currently using to identify a visitor's web browser details. This script is triggered when I make an ajax request. At the end of the PHP script, there is an array, return array( 'userA ...

Does setInterval consume a significant amount of CPU resources?

Recently, I came across an article stating that setInterval is considered to be CPU intensive. To verify this claim, I developed a script utilizing setInterval and closely monitored the CPU usage. Surprisingly, I did not observe any significant changes in ...

Cannot change class until class is reapplied

Is there a way to remove the highlight class before reapplying it to other elements in order to reset the selected items? I tried using removeClass in the code below but it's not working. $("#toggleCustom").on("click", function () { var $this = ...

The carousel comes to a halt once it reaches the final slide and does not continue cycling

Currently working on a website project for a client and utilizing Bootstrap to create a carousel feature. I am specifically using Bootstrap 3.0. After searching for a similar issue here, I found two cases that resemble mine but unfortunately have no soluti ...

Tips for Storing Your Data Collection: A Guide on Different Storage Options

In the different parts of my app, I require access to a dataset containing timezones. Traditionally, I have stored such data in a class method like Timezone.all_zones (Ruby) for easy accessibility anywhere in my code. Is there a way to achieve this same ...

Can we add an opacity filter to the background image?

Is there a way to add opacity to just the background image on my website? I'm looking for a solution that applies the opacity solely to the image area. Check out my JSFiddle for reference. HTML: <header class="main-header " style="background-im ...

Establishing multiple SSH2 connections in Node.js

I need to establish a connection with a remote machine and execute shell commands on it. While I am able to upload a file and run a command successfully, I can only do so once. My goal is to be able to perform these actions multiple times. Below is the Ja ...

Looking to optimize iframing for various screen dimensions

Apologies for the basic question. I am looking for a way to make my iframe responsive on all screen sizes, adjusting both height and width accordingly. Could anyone provide guidance? The current iframe code I have is as follows: <iframe name="ROL_ ...

The font fails to load

I've hit a roadblock with this issue. I'm attempting to add a custom font to my project. The CSS file can be found in the directory project/css/. The font is located at project/fonts/iconfont/. In that folder, I have the following font files (alt ...

Unusual behavior in a for loop with node.js

Trying out some new things with node.js and running into issues with a basic for loop... for (var i = 0; i < 5; i++); {( console.log(i)) } Can anyone explain why I'm seeing 5 in the console? I was anticipating 0,1,2,3,4... ...

Regular Expression, finds occurrences of non-alphabetic characters at least once in a string

I'm encountering difficulties with a certain part of my code, particularly the section within the while loop. public void mSetSafeCode() // Define safe passcode manually { int mIntPasscode; String mStringPasscode; Scanner sc = new Scanner ...

`Select Dropdown Choice will Populate Corresponding Textfields`

While I know this question has been asked multiple times on Stack Overflow, I am looking for a more tailored solution based on my specific requirements. That is why I'm posting this question. I have an HTML form with PHP that retrieves data from an M ...

What is the best way to transfer a JSX element from a child component to its parent component?

Is it acceptable to send the JSX element from a parent component to a child component through props? From my understanding, using `useState` to store JSX elements is not recommended. Therefore, I can't just pass a callback down to the child and then ...

HTML does not get rendered when an Ajax update occurs

<script> function fun() { $.getJSON($SCRIPT_ROOT + '/_add_numbers', {}, function(data) { $("#totalprofit").text(data.total); }); return false; } var interval = setInterval(fun, ...

Enable the duplication of strings within an array

Below is the HTML code snippet I am working with: <div class="col-sm-8"> <div class="row col-sm-12 pull-right paddingDiv"> <div class="col-sm-12"> <div class="marginBottom pull-right"> <bu ...

Issues with -moz-backface-visibility and tailwind css not being compatible

I'm currently facing an issue with the code in my tailwind.config.js file, specifically with the custom class for "moz-backface-visibility" that I've defined. tailwind.config.js /** @type {import('tailwindcss').Config} */ const plugin ...

nodejs error: req.body is not defined

Below is the snippet of HTML code: <form action='/new' method='POST' > <span>Enter pool name: </span> <input type="text" name="name" /> <input type="hidden" name="imageSrcList" /> <button type= ...