diff --git a/index.js b/index.js index 36e7e5d..178b5d7 100644 --- a/index.js +++ b/index.js @@ -1,17 +1,22 @@ - exports = module.exports = trim; function trim(str){ if (str.trim) return str.trim(); - return str.replace(/^\s*|\s*$/g, ''); + return exports.right(exports.left(str)); } exports.left = function(str){ if (str.trimLeft) return str.trimLeft(); - return str.replace(/^\s*/, ''); + + return str.replace(/^\s\s*/, ''); }; exports.right = function(str){ if (str.trimRight) return str.trimRight(); - return str.replace(/\s*$/, ''); + + var whitespace_pattern = /\s/, + i = str.length; + while (whitespace_pattern.test(str.charAt(--i))); + + return str.slice(0, i + 1); }; diff --git a/test/trim.js b/test/trim.js index 8df93f8..6a1a395 100644 --- a/test/trim.js +++ b/test/trim.js @@ -7,6 +7,14 @@ describe('trim(str)', function(){ trim(' foo bar ').should.equal('foo bar'); trim('\n\n\nfoo bar\n\r\n\n').should.equal('foo bar'); }) + + it('should supply implementation of trim() if needed', function() { + var str1 = new String(' foo bar '); + str1.trim = null; + str1.trimLeft = null; + str1.trimRight = null; + trim(str1).should.equal('foo bar'); + }) }) describe('.left(str)', function(){