Trimming a String in JavaScript
This is a nice clean way to implement string trimming for the String object in JavaScript:
-
String.prototype.trim = function()
-
{
-
return this.replace(/^\s+|\s+$/g,"");
-
}
With that implemented, you can then trim a string in the object-oriented way you would prefer and love:
-
var myStr="This is a test! ";
-
alert(myStr.trim());
This is handy for client-side clean-up of form information, although bear in mind that depending on client-side code for data entry clean-up isn't necessarily wise unless you have some server-side code also checking the data.
