Friday, November 19, 2010

Trim function in javascript

To Trim a string using javascript

<script language="JavaScript" type="text/javascript">
String.prototype.trim =
function()
{
str = this;
// remove leading spaces
while(str.substring(0, 1) == ' ')
{
str = str.substring(1, str.length);
}
// remove trailing spaces
while(str.substring(str.length - 1, str.length) == ' ')
{
str = str.substring(0, str.length - 1);
}
return
str;
}
</script>

Usage  :
...
var s = document.forms[0].elements['t1'].value;
alert(s.trim());
....

No comments:

Post a Comment