JavaScript String trim() Method
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.
Supported Browsers
JavaScript String trim() Method- FAQs
What does trim() do in JavaScript?
The trim() method removes whitespace from both sides i.e. from beginning and end of a string. It is useful for sanitizing user input or formatting text.
Does trim() modify the original string?
No, the trim() does not modify the original string. It returns a new string with the whitespace removed from both ends.
How do you trim string from end only?
Use the trimEnd() method to remove only trailing spaces from a string. This leaves the leading whitespace intact.
How does trim() work?
The trim() method scans the string and removes unnecessary white spaces, tabs, or new lines from both ends.
What happens if the string has no leading or trailing whitespace?
If the string has no leading or trailing whitespace, the trim() method returns the original string unchanged.
Does trim() method remove whitespace from the middle of the string?
No, the trim() method only removes whitespace from the beginning and end of the string.
Become an expert in solving problems with DSA JavaScript—the course designed to teach you Data Structures and Algorithms using JavaScript. Over the next 90 days, dive deep into key DSA concepts, learn to optimize your code, and gain hands-on experience solving challenging problems. Whether you're a beginner or looking to refine your JavaScript skills, this course will provide the knowledge you need to succeed.
Take on the Three 90 Challenge today! Complete 90% of the course within 90 days, and you’ll earn a 90% refund. This challenge is your chance to stay motivated, improve your skills, and get rewarded for your progress. Don’t wait—start your journey to DSA mastery with JavaScript today!


