Skip to content

Commit

Permalink
Deprecated: Improve $.trim performance for strings with lots of white…
Browse files Browse the repository at this point in the history
…space

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-5068
  • Loading branch information
vlsi authored Jul 20, 2022
1 parent 410d5cf commit 6994010
Showing 1 changed file with 4 additions and 2 deletions.
6 changes: 4 additions & 2 deletions src/deprecated.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@ define( [

// Support: Android <=4.0 only
// Make sure we trim BOM and NBSP
var rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;
// 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.
var rtrim = /^[\s\uFEFF\xA0]+|([^\s\uFEFF\xA0])[\s\uFEFF\xA0]+$/g;

// Bind a function to a context, optionally partially applying any
// arguments.
Expand Down Expand Up @@ -82,6 +84,6 @@ jQuery.isNumeric = function( obj ) {
jQuery.trim = function( text ) {
return text == null ?
"" :
( text + "" ).replace( rtrim, "" );
( text + "" ).replace( rtrim, "$1" );
};
} );

0 comments on commit 6994010

Please sign in to comment.