Le 12/28/08 12:55 AM, Trevor Lawrence a écrit :
While I appreciate the elegance of the RegExp solutions, there seemed to be
some problems with defining what is white space, so I wondered if the simple
functions below would do the job just as well
Probably they search and eliminate simple white space : ' '
and that doesn't solve the problem to identify other spaces required in
a "trim" function (what to cut of ?).
function trimWhiteSpace(strg) {
return strg.replace(/^ +| +$/g, '');
}
document.write('['+trimWhiteSpace(" Hello world! ")+']');
--> [Hello world!]
function lTrimWS(strg) { return strg.replace(/^ +/, ''); }
function rTrimWS(strg) { return strg.replace(/ +$/, ''); }
If we refer to the PHP trim function(1) we would have to strip from
beginning and end the invisible following characters :
* " " (ASCII 32 (0x20)), an ordinary space.
* "\t" (ASCII 9 (0x09)), a tab.
* "\n" (ASCII 10 (0x0A)), a new line (line feed).
* "\r" (ASCII 13 (0x0D)), a carriage return.
* "\0" (ASCII 0 (0x00)), the NUL-byte.
* "\x0B" (ASCII 11 (0x0B)), a vertical tab.
whom unbreakable space is absent
what is supposed to almost get in reg expression(2) using: \s
witch would have to be equivalent with :
Gecko :
[\t\n\v\f\r
\u00a0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000]
(where \u00a0 is the unbreakable space)
Microsoft :
[\f\n\r\t\v] (and they forget ' ' !)
So we could have :
function trimer( strg, extendedBlanks ) {
var reg = '[\f\n\r\t\v ' + ( extendedBlanks? '\xa0' : '' ) + ']';
reg = new RegExp( '^' + reg + '+|' + reg + '+$', 'g' );
return strg.replace(reg,'');
}
And with the string :
var strng = ' \n\t \n \xa0 hello \xa0 \n \n';
We can get :
document.write('['+ trimer(strng) +']'); // [ hello ]
document.write('['+ trimer(strng,1) +']'); // [hello]
Tested : FF.3, Safari.3, Opera.9, iCab.4
(1)
<
http://fr.php.net/manual/en/function.trim.php>
(2)
<
http://msdn.microsoft.com/en-us/library/se61087k(VS.85).aspx>
<
https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference:Objects:RegExp>