Skip to content

Commit 69a2441

Browse files
authored
Deprecated: Improve $.trim performance for strings with lots of whitespace
Regex imp implementation takes `O(N^2)` time to trim the string when multiple adjacent spaces were present. The new expression require that the "whitespace run" starts from a non-whitespace to avoid `O(N^2)` behavior when the engine would try matching `\s+$` at each space position. Closes gh-461 Ref jquery/jquery#5068
1 parent 8e26772 commit 69a2441

File tree

1 file changed

+4
-4
lines changed

1 file changed

+4
-4
lines changed

src/jquery/core.js

+4-4
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,9 @@ var findProp,
1515
rattrHashTest = /\[(\s*[-\w]+\s*)([~|^$*]?=)\s*([-\w#]*?#[-\w#]*)\s*\]/,
1616
rattrHashGlob = /\[(\s*[-\w]+\s*)([~|^$*]?=)\s*([-\w#]*?#[-\w#]*)\s*\]/g,
1717

18-
// Support: Android <=4.0 only
19-
// Make sure we trim BOM and NBSP
20-
rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;
18+
// Require that the "whitespace run" starts from a non-whitespace
19+
// to avoid O(N^2) behavior when the engine would try matching "\s+$" at each space position.
20+
rtrim = /^[\s\uFEFF\xA0]+|([^\s\uFEFF\xA0])[\s\uFEFF\xA0]+$/g;
2121

2222
migratePatchFunc( jQuery.fn, "init", function( arg1 ) {
2323
var args = Array.prototype.slice.call( arguments );
@@ -109,7 +109,7 @@ if ( jQueryVersionSince( "3.1.1" ) ) {
109109
migratePatchAndWarnFunc( jQuery, "trim", function( text ) {
110110
return text == null ?
111111
"" :
112-
( text + "" ).replace( rtrim, "" );
112+
( text + "" ).replace( rtrim, "$1" );
113113
}, "trim",
114114
"jQuery.trim is deprecated; use String.prototype.trim" );
115115
}

0 commit comments

Comments
 (0)