All whitespace removed and plain text when pasting in all input and text fields

2.5k Views Asked by At

I have seen a few of these question on here and I can not seem to get this to work.

Basically I want the copy and paste events to be plain text only and to remove all white space apart from line breaks and text spaces within the copy and paste process.

(whitespace meaning anything that can not be done using the enter key or spacebar... Things like the tab key etc.)

I need this to happen because this section will be going into a json, and without doing this, it will break the json string.

I will be doing other checks regarding quotes etc.

You can see a jfiddle here

Here is the code I have used:

jQuery(document).ready(function($){

"use strict";

document.querySelector("input, textarea").addEventListener("paste", function(e) {
    e.preventDefault();
    var text = e.clipboardData.getData("text/plain");
    text = text.replace(/^\s+|\s+$/g,'');
    document.execCommand("insertHTML", false, text);
});

});

Thanks in advance for any help provided.

2

There are 2 best solutions below

2
On

Try Following

$(document).on('paste', 'textarea', function(e) {
  e.preventDefault();
  var PlainText = e.originalEvent.clipboardData.getData('Text');
  PlainText = PlainText.replace(/\s+/g, '');
  $(this).val(PlainText);
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea placeholder="Paste Your Text..."></textarea >

4
On
$(document).on('paste', 'textarea', function(e) {
  e.preventDefault();
  var text = e.originalEvent.clipboardData.getData('Text');
  text = text.trim();
  text = text.replace(/\s+/g,' ').trim();
  $(this).val(text);
});

@Robert You can use the .trim() function which can only remove starting and ending spaces. You can replace text = text.trim(); with text = text.replace(/\s+/g,' ').trim(); and it will work for inner text too. I think that's it what u want. If you want anything then fell free to asked.