One simple way of trimming a string is to make use of a powerful regular expressionas opposed to iterating and removing the space characters one by one. To see how this works, save the code below as an
.htm file, and then load the file into IE. Click in the text field and then tab out of it to see the code in action.
<html>
<head>
<title>Trim String</title>
<script language="javascript" type="text/javascript">
function TrimString()
{
var txtObj = document.getElementById("txtTrim");
txtObj.value = txtObj.value.replace(/^\s+/,""); //Left trim
txtObj.value = txtObj.value.replace(/\s+$/,""); //Right trim
}
</script>
</head>
<body>
<input type="text" id="txtTrim" onblur="TrimString(this.value);" />
</body>
</html>
The JS code in the
TrimString function replaces the
space(s) character (identified as
\s in the regular expression) with a blank or empty character.