JavaScript String trim() Method
Last Updated :
28 Oct, 2024
Improve
The trim() method is used to remove the whitespace from both sides of a string. It does not change the original string. It is used for trimming unnecessary spaces from strings or user input data.
Note: This method does not modify the original string, it returns a new trimmed string.
Syntax
str.trim();
Parameters
This method does not accept any parameter.
Return value
Returns a new string without any of the leading or trailing white spaces.
Example 1: Trimming Whitespace from the End of a String.
// String with trailing what spaces
let s = "GeeksforGeeks ";
// trim() method to remove while spaces
let s1 = s.trim();
console.log(s1);
Output
GeeksforGeeks
Example 2: Trimming Leading Whitespace from a String
// Original string with whitespace
let s = " GeeksforGeeks";
// Trimmed string
let s1 = s.trim();
console.log(s1);
Output
GeeksforGeeks
Example 3: Trimming Whitespace from both sides of String
// String with whitespace
let s = " GeeksforGeeks ";
// Trimmed string
let s1 = s.trim();
console.log(s1);
Output
GeeksforGeeks
We have a complete list of Javascript string methods, to check those please go through this JavaScript String Reference article.