Skip to content

Commit 20604d7

Browse files
committed
update String#trim
Check for two commonly erroneously trimmed characters instead of one, and check for erroneously failing to trim the trimmable whitespace characters; then use `aa*` instead of `a+`, and two regexes instead of one, both because they are more performant (it is also more performant to first trim from the beginning and then trim from the end). I would also replace `if (typeof this === 'undefined' || this === null)` with `if (this == null)` but I don't know whether that's allowed by this library's style rules.
1 parent 51eb6c8 commit 20604d7

File tree

1 file changed

+9
-10
lines changed

1 file changed

+9
-10
lines changed

es6-shim.js

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -644,23 +644,22 @@
644644
overrideNative(String.prototype, 'includes', StringPrototypeShims.includes);
645645
}
646646

647-
var hasStringTrimBug = '\u0085'.trim().length !== 1;
647+
// whitespace from: http://es5.github.io/#x15.5.4.20
648+
// implementation from https://github.com/es-shims/es5-shim/blob/v3.4.0/es5-shim.js#L1304-L1324
649+
var ws = '\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003\u2004' +
650+
'\u2005\u2006\u2007\u2008\u2009\u200A\u2028\u2029\u202F\u205F\u3000\uFEFF';
651+
var hasStringTrimBug = ws.trim() || '\u0085\u002B'.trim().length !== 2;
648652
if (hasStringTrimBug) {
649653
delete String.prototype.trim;
650-
// whitespace from: http://es5.github.io/#x15.5.4.20
651-
// implementation from https://github.com/es-shims/es5-shim/blob/v3.4.0/es5-shim.js#L1304-L1324
652-
var ws = [
653-
'\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003',
654-
'\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028',
655-
'\u2029\uFEFF'
656-
].join('');
657-
var trimRegexp = new RegExp('(^[' + ws + ']+)|([' + ws + ']+$)', 'g');
654+
var wsRegexpChars = '[' + ws + '][' + ws + ']*';
655+
var trimBeginRegexp = new RegExp('^' + wsRegexChars);
656+
var trimEndRegexp = new RegExp(wsRegexChars + '$');
658657
defineProperties(String.prototype, {
659658
trim: function trim() {
660659
if (typeof this === 'undefined' || this === null) {
661660
throw new TypeError("can't convert " + this + ' to object');
662661
}
663-
return String(this).replace(trimRegexp, '');
662+
return String(this).replace(trimBeginRegexp, '').replace(trimEndRegexp, '');
664663
}
665664
});
666665
}

0 commit comments

Comments
 (0)