JavaScript trimEnd() method
The trimEnd()
(also known as trimRight()
) method in JavaScript is used to remove whitespace from the end of a string. This includes spaces, tabs, and newline characters. It is particularly useful for cleaning up user input or formatting strings where trailing whitespace may cause issues.
Syntax:
or
Both methods perform the same function, and you can use either one based on your preference. However, trimEnd()
is the more modern name.
Return Value:
- Returns a new string with whitespace removed from the end. The original string remains unchanged.
Example 1: Basic Usage
In this example, the trailing spaces in the string " Hello, World! "
are removed, resulting in " Hello, World!"
.
Example 2: No Trailing Whitespace
If there is no trailing whitespace, trimEnd()
will return the original string unchanged.
Example 3: Whitespace Only
If the string consists entirely of trailing whitespace, trimEnd()
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 trimEnd()
method.
Example 5: Differences with trim()
While trim()
removes whitespace from both ends of a string, trimEnd()
only affects the end.
Summary:
- The
trimEnd()
(ortrimRight()
) method removes whitespace from the end of a string. - It returns a new string without modifying the original string.
- If there is no trailing whitespace, the original string is returned unchanged.
- If the string consists only of trailing whitespace, an empty string is returned.
- This method is useful for cleaning up user input or formatting strings where trailing whitespace may cause issues.