How jQuery $.trim() Handles Strings

The jQuery $.trim() function is a core utility designed to remove leading and trailing whitespace from a given value. This article explains how $.trim() processes string data, handles non-string and falsy inputs, matches different whitespace characters, and compares to modern native JavaScript alternatives.

Basic String Handling

At its core, $.trim() takes a string argument and strips all whitespace from the beginning and end of that string, leaving any whitespace between characters intact.

var result = $.trim("   Hello World!   ");
// Output: "Hello World!"

The function removes standard space characters, horizontal tabs (\t), line feeds (\n), carriage returns (\r), and other Unicode whitespace equivalents such as non-breaking spaces (\xA0) and zero-width spaces (\uFEFF).

Handling Non-String and Falsy Inputs

One of the main advantages $.trim() had over standard methods during its introduction was its safe handling of null and undefined values.

  • Null and Undefined: If you pass null or undefined to $.trim(), it does not throw an error. Instead, it safely returns an empty string ("").
  • Numbers and Booleans: If a non-string primitive is passed, jQuery converts it to a string representation before applying the trim. For example, $.trim(123) returns "123", and $.trim(true) returns "true".
  • Objects and Arrays: Passing complex types invokes their standard .toString() conversion, after which the resulting string is trimmed.

Internal Implementation

In early versions of jQuery, $.trim() relied on regular expressions to detect and remove whitespace characters:

rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;

In later versions, jQuery updated $.trim() to delegate directly to the native ECMAScript 5 String.prototype.trim() method whenever available, while still maintaining null-safety checks:

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

Deprecation and Native JavaScript Alternative

Starting in jQuery 3.5.0, $.trim() was officially deprecated because all modern JavaScript environments natively support String.prototype.trim().

To achieve the same behavior using modern standard JavaScript without jQuery, you can use the optional chaining operator or a fallback check to prevent errors on nullish values:

const cleanString = (value ?? "").toString().trim();