faqts : Computers : Programming : Languages : JavaScript : Forms : TextAreas/TextFields

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

43 of 51 people (84%) answered Yes
Recently 9 of 10 people (90%) answered Yes

Entry

How can I remove spaces from the value of a text field if one is detected (IE; between words, not just at the end)

Dec 3rd, 2001 03:20
Dan, James Martens,


You can use "replace" method (part of String).

Example:

<html>
<head>
<script language="javascript">
function trim() {
  // remove all spaces from aText text field 
  // and place the result into the right text field
  document.aForm.aTextWithNoSpaces.value = 
        document.aForm.aText.value.replace(/ /g, "");
} // trim

</script>
</head>

<body>
<form name="aForm">
<input type="text" name="aText">

<input type="button" name="aButton" value="Remove all spaces" 
       onClick = "trim()">

<input type="text" name="aTextWithNoSpaces">
</form>
</body
</html>