[Javascript] trim function (regex)

jsWalter jsWalter at torres.ws
Wed May 5 14:04:43 CDT 2004


OK, since you  offered...

This adds it as a new method off the String Object.

Walter

===============================

// remove White Space from start and/or end of given string
String.prototype.trim  = _trim;

/**
  * remove White Space from start and/or end of given string
  * White Space is defined as:
  *         - Space
  *        - Carriage Return
  *        - newline
  *        - form feed
  *        - TABs
  *        - Vertical TABs
  **/

function _trim ( )
{
   //   /            open search
   //     ^            beginning of string
   //     \s           find White Space, space, TAB and Carriage Returns
   //     +            one or more
   //   |            logical OR
   //     \s           find White Space, space, TAB and Carriage Returns
   //     $            at end of string
   //   /            close search
   //   g            global search

   return this.replace(/^\s+|\s+$/g, "");
}

// Test this
var strDemo  = '   something   ';
var strStrip = strDemo.trim();

alert ( '|' + strDemo + '|\n' + '|' + strStrip + '|');

==========================





More information about the Javascript mailing list