Skip to content

Commit 496fc8b

Browse files
authored
fix(rtrim): remove regex to prevent ReDOS attack (#1738)
1 parent 45901ec commit 496fc8b

File tree

1 file changed

+12
-3
lines changed

1 file changed

+12
-3
lines changed

Diff for: src/lib/rtrim.js

+12-3
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,16 @@ import assertString from './util/assertString';
22

33
export default function rtrim(str, chars) {
44
assertString(str);
5-
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#Escaping
6-
const pattern = chars ? new RegExp(`[${chars.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}]+$`, 'g') : /(\s)+$/g;
7-
return str.replace(pattern, '');
5+
if (chars) {
6+
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#Escaping
7+
const pattern = new RegExp(`[${chars.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}]+$`, 'g');
8+
return str.replace(pattern, '');
9+
}
10+
// Use a faster and more safe than regex trim method https://blog.stevenlevithan.com/archives/faster-trim-javascript
11+
let strIndex = str.length - 1;
12+
while (/\s/.test(str.charAt(strIndex))) {
13+
strIndex -= 1;
14+
}
15+
16+
return str.slice(0, strIndex + 1);
817
}

0 commit comments

Comments
 (0)