Cristian Crishk Cristian Crishk - 1 year ago 81
Javascript Question

How to remove/trim spaces or tabs while writing?

I'm trying to trim a String using javascript (in jQuery) while the user is writing:

$(document).on('keydown', "input[type='text'], textarea", function(e) {
$(this).val( $(this).val().trim() );
//if ($(this).val() == "") {
} );

But the problem here is when the user writes a space to write another word, this code trims the data in the input and the next word is concatenated like:


Really what I need is to remove the tabs or the spaces when the user texts using CTRL+V from clipboard.

Can you help?

Answer Source

I think this is what you need. Look for repeated space chars. Preserve the last one and remove others. String.replace with RegExp can handle this.

Also I used keyup event instead of keydown

$(document).on('keyup', "input[type='text'], textarea", function(e) {
  let val = $(this).val();
  val = val.replace(/(?:^\s+|\s+?(\s))(\S+)/g, "$1$2");
  val = val.replace(/\s+(\s)$/, "$1"); 
  $(this).val( val );
 } );
<script src=""></script>
<textarea cols="40" rows="10"></textarea>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download