Last Updated : 28 Oct, 2024
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.
SyntaxNote: This method does not modify the original string, it returns a new trimmed string.
str.trim();Parameters
This method does not accept any parameter.
Return valueReturns a new string without any of the leading or trailing white spaces.
Example 1: Trimming Whitespace from the End of a String.
JavaScript
// String with trailing what spaces
let s = "GeeksforGeeks ";
// trim() method to remove while spaces
let s1 = s.trim();
console.log(s1);
Example 2: Trimming Leading Whitespace from a String
JavaScript
// Original string with whitespace
let s = " GeeksforGeeks";
// Trimmed string
let s1 = s.trim();
console.log(s1);
Example 3: Trimming Whitespace from both sides of String
JavaScript
// String with whitespace
let s = " GeeksforGeeks ";
// Trimmed string
let s1 = s.trim();
console.log(s1);
We have a complete list of Javascript string methods, to check those please go through this JavaScript String Reference article.
Supported BrowsersRetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4