File tree Expand file tree Collapse file tree 2 files changed +39
-3
lines changed
Expand file tree Collapse file tree 2 files changed +39
-3
lines changed Original file line number Diff line number Diff line change 11'use strict' ;
22
3- var regex = / ^ (?: \r | \n ) + | (?: \r | \n ) + $ / g;
3+ var regex = / [ ^ \r \n ] / g;
44
55module . exports = function ( str ) {
6- return str . replace ( regex , '' ) ;
6+ var result = regex . exec ( str ) ;
7+ if ( ! result ) {
8+ return '' ;
9+ }
10+ var firstIndex = result . index ;
11+ var lastIndex ;
12+ while ( result ) {
13+ lastIndex = result . index + 1 ;
14+ result = regex . exec ( str ) ;
15+ }
16+ return str . substring ( firstIndex , lastIndex ) ;
717} ;
Original file line number Diff line number Diff line change @@ -21,8 +21,34 @@ it('should trim off \\r\\n', function () {
2121} ) ;
2222
2323it ( 'should not be susceptible to exponential backtracking' , function ( ) {
24+ var redosString = 'a' ;
25+ var count = 1000 ;
26+ while ( count ) {
27+ redosString += '\r\n' ;
28+ count -- ;
29+ }
30+ redosString += 'a' ;
31+ var LongerRedosString = redosString ;
32+ var count = 1000 ;
33+ while ( count ) {
34+ LongerRedosString += redosString ;
35+ count -- ;
36+ }
2437 var start = Date . now ( ) ;
25- trimOffNewlines ( 'a' + '\r\n' . repeat ( 1000 ) + 'a' ) ;
38+ trimOffNewlines ( redosString ) ;
39+ trimOffNewlines ( LongerRedosString ) ;
2640 var end = Date . now ( ) ;
2741 assert . ok ( end - start < 1000 , 'took too long, probably susceptible to ReDOS' ) ;
2842} ) ;
43+
44+ it ( 'should leave newlines in the middle of a string alone' , function ( ) {
45+ assert . strictEqual ( trimOffNewlines ( 'Come on,\nFhqwhgads.' ) , 'Come on,\nFhqwhgads.' ) ;
46+ } ) ;
47+
48+ it ( 'should leave spaces at start and end alone' , function ( ) {
49+ assert . strictEqual ( trimOffNewlines ( ' fhqwhgads ' ) , ' fhqwhgads ' ) ;
50+ } ) ;
51+
52+ it ( 'should return an empty string if there are only \\r and \\n' , function ( ) {
53+ assert . strictEqual ( trimOffNewlines ( '\r\n\r\r\n\n' ) , '' ) ;
54+ } ) ;
You can’t perform that action at this time.
0 commit comments