JavaScript trimStart() method


The trimStart() (also known as trimLeft()) method in JavaScript is used to remove whitespace from the beginning of a string. This includes spaces, tabs, and newline characters. It's particularly useful for cleaning up user input or formatting strings where leading whitespace may cause issues.

Syntax:

string.trimStart()

or

string.trimLeft()

Both methods perform the same function, and you can use either one based on your preference. However, trimStart() is the more modern name.

Return Value:

  • Returns a new string with whitespace removed from the start. The original string remains unchanged.

Example 1: Basic Usage

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

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

Example 2: No Leading Whitespace

If there is no leading whitespace, trimStart() will return the original string unchanged.

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

Example 3: Whitespace Only

If the string consists entirely of leading whitespace, trimStart() will remove all of it.

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

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

Example 4: Original String Remains Unchanged

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

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

Example 5: Differences with trim()

While trim() removes whitespace from both ends of a string, trimStart() only affects the beginning.

let str = " Hello! "; let trimmedBoth = str.trim(); let trimmedStart = str.trimStart(); console.log(trimmedBoth); // "Hello!" (whitespace removed from both ends) console.log(trimmedStart); // "Hello! " (whitespace removed only from the start)

Summary:

  • The trimStart() (or trimLeft()) method removes whitespace from the beginning of a string.
  • It returns a new string without modifying the original string.
  • If there is no leading whitespace, the original string is returned unchanged.
  • If the string consists only of leading whitespace, an empty string is returned.
  • This method is useful for cleaning up user input or formatting strings where leading whitespace may cause issues.