Yesterday, some one asked me how to remove whitespaces at beginging and end of a string in javascript. So, i decided to make a trim function which will remove whitespaces from begining and end of a string.
Here's an example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script language="javascript">
function LTrim(value) {
var re = /\s*((\S+\s*)*)/;
return value.replace(re, "$1");
}
function RTrim(value) {
var re = /((\s*\S+)*)\s*/;
return value.replace(re, "$1");
}
function trim(value) {
return LTrim(RTrim(value));
}
function getValue() {
var username = trim(document.getElementById('<%=TextBox1.ClientID %>').value);
if (username != '')
alert(username);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
Username:
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<input id="Button2" type="button" value="Submit" onclick="return getValue();" />
</div>
</form>
</body>
</html>
Output

Download
Trim function.zip (894.00 bytes)
Live demo