JavaScript String.trim() Method
-
Syntax of JavaScript
string.trim()
: -
Example Codes: Use the
string.trim()
Method to Remove White Space From Both Ends of a String -
Example Codes: Use the
string.trimRight()
Method to Only Remove White Space From the Right Part
The string.trim()
method keeps the original content unchanged while removing the white space character from the start and end parts. On the other hand, string.trimLeft()
and string.trimRight()
can remove white space from only the left or right part of the string, respectively.
Syntax of JavaScript string.trim()
:
refString.trim();
refString.trimRight();
Parameter
This method does not take any parameters.
Return
It returns the strings without white space at both ends.
Example Codes: Use the string.trim()
Method to Remove White Space From Both Ends of a String
While writing content online, we might include white space at the beginning sentence and the ending part. Using the string.trim()
function, we can remove those characters from the string.
In the example below, we have used string.trim()
for the string without any parameter.
let str =" This is a sentence. ";
console.log(str.trim());
Output:
This is a sentence.
Example Codes: Use the string.trimRight()
Method to Only Remove White Space From the Right Part
There might be a requirement for white space at the beginning of a paragraph. So, in this example, we will remove white space characters from the ending part.
In the string, we have used white space on both ends. However, by using the string.trimRight()
method, we will remove white space from the right side only.
let str =" This is a paragraph. ";
let restr = str.trimRight();
console.log(restr);
Output:
This is a paragraph.
The string.trim()
method removes any white space found in the beginning or ending part of a string, including tab and no-break space. This method is supported in most modern browsers.