Trim Whitespace with trim()
Write a JavaScript function that takes a string and returns a new string with leading and trailing whitespace removed using String.trim(). Whitespace includes spaces, tabs, newlines, carriage returns, and other Unicode whitespace characters.
String.prototype.trim() is a JavaScript method that removes whitespace from both ends of a string. It returns a new string without modifying the original. The method was introduced in ES5 and is available in all modern JavaScript environments. It complements trimStart() and trimEnd() for one-sided trimming.
The trim() method is commonly used for cleaning user input from forms, processing CSV data, and normalizing strings before comparison or storage. The method handles all Unicode whitespace characters defined by the ECMAScript specification, including non-breaking spaces and zero-width joiners in some implementations.
Time complexity is O(n) where n is the string length. Space complexity is O(k) where k is the trimmed string length. The method scans from both ends to find the first and last non-whitespace characters.
Edge cases include strings with only whitespace (returns empty string), strings with no whitespace (returns the original string unchanged), strings with internal whitespace (internal spaces are preserved, only leading/trailing are removed), and empty strings (returns empty string).
Example Input & Output
All whitespace becomes empty
Internal spaces preserved
Trim tabs and newlines
Trim both sides
No whitespace, unchanged
Algorithm Flow

Solution Approach
Best Answers
function solution(str) {
return str.trim();
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
