Remove spaces from an input field with JavaScript

By | December 10, 2008

This is a small snippet to remove the spaces from an input field using JavaScript. It can be useful when you want a value without spaces, or when you want to replace the spaces from the input field with other characters.

The JavaScript code:

function stripspaces(input)
{
  input.value = input.value.replace(/\s/gi,"");
  return true;
}

The input field:

<input onkeydown="javascript:stripspaces(this)" name="field_with_no_spaces" type="text" />

The spaces will be stripped from the input field in real-time, as the user types.

11 thoughts on “Remove spaces from an input field with JavaScript

  1. Matt Smith (@mattsmith24)

    I must have searched through a hundred sites on Google for this, and yours is the only one that actually worked. THANK YOU. (P.s. onKeyUp works quite nicely too)

  2. Giovka

    Thank you, works good, but unfortunately not removes the space when it’s at the end of a string (for example: if you not remove the space at the end of an email address, this will not valid for the regex that checks the field.
    I’m a beginner with the regex, someone know how to do that?

Leave a Reply