Trimming a String in JavaScript

This is a nice clean way to implement string trimming for the String object in JavaScript:

JavaScript:
  1. String.prototype.trim = function()
  2. {
  3.    return this.replace(/^\s+|\s+$/g,"");
  4. }

With that implemented, you can then trim a string in the object-oriented way you would prefer and love:

JavaScript:
  1. var myStr="This is a test!   ";
  2. 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.

  Theme Brought to you by Directory Journal and Elegant Directory.