This repository was archived by the owner on Feb 25, 2023. It is now read-only.
File tree Expand file tree Collapse file tree 2 files changed +17
-4
lines changed
Expand file tree Collapse file tree 2 files changed +17
-4
lines changed Original file line number Diff line number Diff line change 1-
21exports = module . exports = trim ;
32
43function trim ( str ) {
54 if ( str . trim ) return str . trim ( ) ;
6- return str . replace ( / ^ \s * | \s * $ / g , '' ) ;
5+ return exports . right ( exports . left ( str ) ) ;
76}
87
98exports . left = function ( str ) {
109 if ( str . trimLeft ) return str . trimLeft ( ) ;
11- return str . replace ( / ^ \s * / , '' ) ;
10+
11+ return str . replace ( / ^ \s \s * / , '' ) ;
1212} ;
1313
1414exports . right = function ( str ) {
1515 if ( str . trimRight ) return str . trimRight ( ) ;
16- return str . replace ( / \s * $ / , '' ) ;
16+
17+ var whitespace_pattern = / \s / ,
18+ i = str . length ;
19+ while ( whitespace_pattern . test ( str . charAt ( -- i ) ) ) ;
20+
21+ return str . slice ( 0 , i + 1 ) ;
1722} ;
Original file line number Diff line number Diff line change @@ -7,6 +7,14 @@ describe('trim(str)', function(){
77 trim ( ' foo bar ' ) . should . equal ( 'foo bar' ) ;
88 trim ( '\n\n\nfoo bar\n\r\n\n' ) . should . equal ( 'foo bar' ) ;
99 } )
10+
11+ it ( 'should supply implementation of trim() if needed' , function ( ) {
12+ var str1 = new String ( ' foo bar ' ) ;
13+ str1 . trim = null ;
14+ str1 . trimLeft = null ;
15+ str1 . trimRight = null ;
16+ trim ( str1 ) . should . equal ( 'foo bar' ) ;
17+ } )
1018} )
1119
1220describe ( '.left(str)' , function ( ) {
You can’t perform that action at this time.
0 commit comments