javascriptjquery

jQuery.trim() deprecated, but suggested replacement isn't the same?


The following code:

if (!value || $.trim(value).length === 0)
    return true;

Produces the following warning.

(JS) The signature '(str: string): string' of '$.trim' is deprecated.

The recommended fix says to use the native String.prototype.trim method instead.

But $.trim(value) is not equal to value.trim(). The first version works with types other than strings (null, undefined, Number). The second version requires a string.

Has it been documented why this jQuery.trim() is deprecated when there isn't a direct replacement? And does anyone have a good replacement for it?


Solution

  • The implementation of $.trim() is

        trim: function( text ) {
            return text == null ?
                "" :
                ( text + "" ).replace( rtrim, "" );
        },
    

    This is roughly equivalent to String(text).trim(), but the conditional avoids converting null and undefined to the strings "null" and `"undefined". Trimming them returns an empty string.

    A simple way to write this in modern JS would be

    jQuery.trim = text => String(text ?? "").trim();
    

    The jQuery code predates the ?? null coalescing operator.