From 699401008fbc6cdfc5d6a1d531e1bc5013a94bec Mon Sep 17 00:00:00 2001 From: Vladimir Sitnikov Date: Wed, 20 Jul 2022 11:51:13 +0300 Subject: [PATCH] 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-5068 --- src/deprecated.js | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/deprecated.js b/src/deprecated.js index cc13c3c82..ca54982d7 100644 --- a/src/deprecated.js +++ b/src/deprecated.js @@ -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. @@ -82,6 +84,6 @@ jQuery.isNumeric = function( obj ) { jQuery.trim = function( text ) { return text == null ? "" : - ( text + "" ).replace( rtrim, "" ); + ( text + "" ).replace( rtrim, "$1" ); }; } );