Description

The JavaScript String method trim() removes whitespace from both ends (both leading and trailing) of a string.

  • It returns a new string and doesn't change the original string.
  • The returned string has whitespace stripped from both ends of a string.
  • The whitespace characters include space, tab, no-break space, and line terminator characters like LF (line feed \n), CR (carriage return \r), etc.,

Syntax

The method trim() has the below syntax, where str is a string.

str.trim()

Parameters

The method trim() doesn't allow any parameters.

Result

Returns a new string with whitespace stripped from both the ends of the string str.

It doesn't change the original string.

Example 1: Using the Method

The below example shows the basic usage of the method.

var str1 = "        Learning JavaScript is fun";
var str2 = "Learning JavaScript is fun            ";
var str3 = "        Learning JavaScript is fun            ";
var str4 = "        Learning     JavaScript is     fun            ";

// Strips leading spaces
document.write(str1.trim(str));    // Prints: Learning JavaScript is fun

// Strips trailing spaces
document.write(str2.trim(str));    // Prints: Learning JavaScript is fun

// Strips both leading and leading spaces
document.write(str3.trim(str));    // Prints: Learning JavaScript is fun

// Retains spaces between the words of a string
document.write(str4.trim(str));    // Prints: Learning     JavaScript is     fun

Output:

Learning JavaScript is fun
Learning JavaScript is fun
Learning JavaScript is fun
Learning     JavaScript is     fun

Overall

The JavaScript String method trim() removes whitespace from both ends (both leading and trailing) of a string.

Related Links