function trim(str)
{
var startpatt = /^\s/;
var endpatt = /\s$/;
while(str.search(startpatt) == 0)
str = str.substring(1, str.length);
while(str.search(endpatt) == str.length-1)
str = str.substring(0, str.length-1);
return str;
}
function submittrim(form)
{
for (var i = 0; i<form.elements.length; i++)
{
if(form.elements[i].value != '' && form.elements[i].type == 'text' )
{
form.elements[i].value = trim(form.elements[i].value);
}
}
return true;
}
</eeSnippet>
And you can trigger the call with the onSubmit event in your form declaration.
[code]
<form method="POST" action="test.do" onsubmit="return submittrim(this);">
Have a question about something in this article? You can receive help directly from the article author. Sign up for a free trial to get started.
Comments (6)
Commented:
String.prototype.trim = function()
{
return this.replace(/^\s+/g, "").replace(/\s+$/g, "");
}
Commented:
function trim(str) {
return str.replace(/^\s+|\s+$/g,"
}
why introduce a loop into a process when there are better methods
Commented:
if (form.elements[i].type == 'text' && form.elements[i].value != '')
Actually, you should rather specify what fields you want to apply trimming to rather than trying to apply it everywhere that it's possible.
Commented:
function RTrim( value ) { var re = /((\s*\S+)*)\s*/; return value.replace(re, "$1"); }
function trim( value )
{
var value = value.replace(/\s\s+/g, ' ');
return LTrim(RTrim(value));
}
Commented:
View More