Skip to content
This repository was archived by the owner on Feb 25, 2023. It is now read-only.

Commit 52b0acc

Browse files
patsplatTrott
authored andcommitted
1 parent b46308e commit 52b0acc

File tree

2 files changed

+17
-4
lines changed

2 files changed

+17
-4
lines changed

index.js

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,22 @@
1-
21
exports = module.exports = trim;
32

43
function 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

98
exports.left = function(str){
109
if (str.trimLeft) return str.trimLeft();
11-
return str.replace(/^\s*/, '');
10+
11+
return str.replace(/^\s\s*/, '');
1212
};
1313

1414
exports.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
};

test/trim.js

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff 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

1220
describe('.left(str)', function(){

0 commit comments

Comments
 (0)