1

I'm trying to remove line breaks in a contenteditable with a regular expresion when users paste text.

The problem is that the regex only works after the second time you paste something. I also the need keyup and keypress events for other things that aren't in the example (character count for limit).

What's wrong with my code?

$(document).on("keyup keypress paste", "#myContentEditable", function(e) {
  if (e.type === "paste") {
    $(this).html($(this).text().replace(/[\n\r]/g, ""));
  }

  if (e.which === 13) {
    e.preventDefault();
    return false;
  }
});
#myContentEditable {
  border: 1px solid lightblue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="myContentEditable" contenteditable="plaintext-only" max="130" contenteditable="true">This is content editable. Remove break lines of the pasted text only works at the second time</div>
<hr>
<p>Try to paste this text:</p>
<p>Massa enim nec dui nunc mattis enim ut tellus elementum. Accumsan sit amet nulla facilisi morbi tempus iaculis urna id.<br><br> Nunc lobortis mattis aliquam faucibus purus in massa.</p>
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
SilverSurfer
  • 4,281
  • 6
  • 24
  • 50

1 Answers1

3

The issue is because the paste event fires before the actual HTML of the contenteditable div has been updated.

You can fix this by using the input event instead:

$(document).on("input", "#myContentEditable", function(e) {
  $(this).html($(this).text().replace(/[\n\r]/g, ""));
});
#myContentEditable {
  border: 1px solid lightblue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="myContentEditable" contenteditable="plaintext-only" max="130" contenteditable="true">This is content editable. Remove break lines of the pasted text only works at the second time</div>
<hr>
<p>Try to paste this text:</p>
<p>Massa enim nec dui nunc mattis enim ut tellus elementum. Accumsan sit amet nulla facilisi morbi tempus iaculis urna id.<br><br> Nunc lobortis mattis aliquam faucibus purus in massa.</p>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339