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

Commit

Permalink
Fix possible regex dos vulnerability.
Browse files Browse the repository at this point in the history
  • Loading branch information
patsplat authored and Trott committed Nov 4, 2020
1 parent b46308e commit 52b0acc
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 4 deletions.
13 changes: 9 additions & 4 deletions 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);
};
8 changes: 8 additions & 0 deletions test/trim.js
Expand Up @@ -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(){
Expand Down

0 comments on commit 52b0acc

Please sign in to comment.