Cristian Crishk Cristian Crishk - 6 days ago 5
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() );
console.log('fixing');
//if ($(this).val() == "") {
//alert('gwo!');
//}
} );


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:

I'mbigandgreat

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

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="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea cols="40" rows="10"></textarea>