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:
or
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
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.
Example 3: Whitespace Only
If the string consists entirely of leading whitespace, trimStart()
will remove all of it.
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.
Example 5: Differences with trim()
While trim()
removes whitespace from both ends of a string, trimStart()
only affects the beginning.
Summary:
- The
trimStart()
(ortrimLeft()
) 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.