JavaScript trim() method


The trim() method in JavaScript is used to remove whitespace from both ends of a string. This includes spaces, tabs, and newline characters. The method is particularly useful for cleaning up user input or formatting strings before processing them.

Syntax:

string.trim()

Return Value:

  • Returns a new string with whitespace removed from both the beginning and the end. The original string remains unchanged.

Example 1: Basic Usage

let str = " Hello, World! "; let trimmedStr = str.trim(); console.log(trimmedStr); // "Hello, World!"

In this example, the leading and trailing spaces in the string " Hello, World! " are removed, resulting in "Hello, World!".

Example 2: No Whitespace

If there is no whitespace at the start or end of the string, trim() will return the original string unchanged.

let str = "Hello, World!"; let trimmedStr = str.trim(); console.log(trimmedStr); // "Hello, World!" (no change)

Example 3: Whitespace Only

If the string consists entirely of whitespace, trim() will return an empty string.

let str = " "; let trimmedStr = str.trim(); console.log(trimmedStr); // "" (an empty string)

In this case, the original string contains only spaces, so the result is an empty string.

Example 4: Using with User Input

The trim() method is commonly used to clean up user input before processing.

let userInput = " example@example.com "; let cleanedInput = userInput.trim(); console.log(cleanedInput); // "example@example.com"

Here, leading and trailing spaces from an email address entered by the user are removed.

Example 5: Original String Remains Unchanged

The original string is not modified by the trim() method.

let str = " Hello! "; let trimmedStr = str.trim(); console.log(str); // " Hello! " (original string remains unchanged) console.log(trimmedStr); // "Hello!" (new trimmed string)

Summary:

  • The trim() method removes whitespace from both ends of a string.
  • It returns a new string without modifying the original string.
  • If there is no whitespace, the original string is returned unchanged.
  • If the string consists only of whitespace, an empty string is returned.
  • This method is particularly useful for cleaning up user input and formatting strings.