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.

3 Responses to “Trimming a String in JavaScript”

  1. Jennifer Says:

    http://xkcd.com/208/

    The same solution with straight up JavaScript is like 30 or 40 lines. I had a function to do this and had found the trimming regular expression and laughed at the glaring difference. Regular expressions are amazing.

  2. Josh Says:

    Lol I love it. I still have plenty of legacy code with dozens of lines manipulating strings to pull out various bits of data that would be accessible in a line or two of RegEx. Amazing.

    Apparently there is some controversy over the exact RegEx to most efficiently trim, depending on what level of white space you trim out. I’m not so picky, I was using it to trim content from an input form field, so there isn’t much more than spaces to worry about. :-)

  3. Josh Says:

    The code view plugin for WP apparently gobbled up the backslashes in the code for the trimming function. It’s correct now. Thanks Ray.

Leave a Reply

  Theme Brought to you by Directory Journal and Elegant Directory.