jQuery

Remove the leading and trailing space

JS

<script>
$('#myInput').on('blur', function() {

 var inputValue = $(this).val();
 var trimmedValue = inputValue.replace(/^\s+|\s+$/g, '');
 
$(this).val(trimmedValue);

}); 
</script>

Explanation:

  • $('#myInput').on('blur', function() {...});: This listens for when the input field loses focus (blur event).
  • $(this).val(): Retrieves the current value of the input field.
  • replace(): Removes any leading or trailing spaces from the input string.
  • $(this).val(trimmedValue): Updates the input field with the trimmed value.