Monday, September 05, 2005

ASP.NET TextBox, Trim White Spaces within words

ASP.NET TextBox provides a lot of features which reduces many a plumbing work required in previous versions of HTML Input Type.

Some of the built-in functionalities of <asp:textbox> such as TextMode to specify whether it is a Text field, a password field or Text Area simplify the programming task and provide meaningful interfaces to work with.

One of the important tasks we do when receiving user input in TextBox is to Trim the white spaces entered by the users. This can very well minimize the size of the data as well as storage in DataStores.

Some of the built-in methods that ship with the string class are


Removes the specified set of occurances from the Beginning of the string


Removes the specified set of occurances from the End of the string


Removes White Spaces from Beginning & End of the string. Very useful in applications while retrieving user input to remove the white spaces.

To utilize the above functions with TextBox input entered by the users, we can simply pass TextBox1.Text.Trim(). Since TextBox1.Text returns a string of the text entered by the user.

However, if we would like to trim the extra white spaces entered by the users in the TextBox in the form of a sentence etc., then the above methods would'nt be useful.

Say the user has entered "This       is     a     Word". We would like to save it/process it as "This is a Word", with the extra white spaces trimmed off.

To do that, we can use RegularExpressions. The following code demonstrates how we can remove extra white spaces recursively between words.

using System.Text.RegularExpressions;

private string RemoveSpaces(string str)
string result = "";
Regex regulEx = new Regex(@"[\s]+");
result = regulEx.Replace(str," ");
return result;

The above function receives a string and trims all the occurances of extra white spaces between words.

So, an input of "This       is     a     Word" will return the output as "This is a Word"