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

  • Has it been documented why this jQuery.trim() is deprecated

    In summary: it's not a DOM manipulation method, which is the primary purpose of jQuery and there's a now a built-in/native alternative (see other answer for details).

    Following the trail:

    https://api.jquery.com/jQuery.trim/

    Note: This API has been deprecated in jQuery 3.5; please use the native String.prototype.trim method instead. Unlike jQuery.trim, String.prototype.trim does not work with types other than strings (null, undefined, Number). Make sure that your code is compatible when migrating.

    https://api.jquery.com/category/deprecated/deprecated-3.5/

    For more information, see the Release Notes/Changelog at

    https://blog.jquery.com/2020/04/10/jquery-3-5-0-released/

    In jQuery 3.5.0, we’ve put jQuery.trim [link to pull request] on the list. JavaScript’s own String.prototype.trim() is an easy replacement for it.

    https://github.com/jquery/jquery/pull/4461

    .. mentioned this pull request on

    https://github.com/jquery/jquery/issues/4363

    jQuery.trim was useful for IE <9 and later to workaround an old Android Browser issue but we don't support that browsers anymore on master. It also adds one niceity[sic] that it accepts a null value that it turns to an empty string but that's it. Should we deprecate it?

    ... I'd actually prefer that people used the built-in methods rather than our utilities ... we don't actually need to remove it but could signal there are alternatives by deprecating.

    ... we should be discouraging use of nonstandard patterns where standard ones exist (especially when the don't pertain to the primary purpose of this library).