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:
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
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.
Example 3: Whitespace Only
If the string consists entirely of whitespace, trim()
will return 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.
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.
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.