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.
var txtObj = document.getElementById("txtTrim");
txtObj.value = txtObj.value.replace(/^\s+/,""); //Left trim
txtObj.value = txtObj.value.replace(/\s+$/,""); //Right trim
<input type="text" id="txtTrim" onblur="TrimString(this.value);" />
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.