星期五, 五月 14, 2004

如何在Javascript压缩(trim)空格

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 + '|');