Strip white spaces on input

Use jQuery trim to remove leading and trailing white space

$.trim(" test case "); // 'test case'

To remove all whitespace...

" test   ing  ".replace(/\s+/g, ''); // 'testing'

To remove whitespace as it is entered...

$(function(){
  $('#noSpacesField').bind('input', function(){
    $(this).val(function(_, v){
      return v.replace(/\s+/g, '');
    });
  });
});

Live Example


$('#noSpacesField').keyup(function() {
  $(this).val($(this).val().replace(/ +?/g, ''));
});

This will remove spaces as you type, and will also remove the tab char.

Tags:

Jquery