Trim Whitespace (JavaScript)
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
Remove whitespace from both ends of a string using the trim() method. This method returns a new string with leading and trailing whitespace characters removed. Whitespace includes spaces, tabs, and newlines. The original string is not modified since strings are immutable in JavaScript.
The trim() method is the cleanest way to strip whitespace. Alternatives like replace(/^\s+|\s+$/g, '') achieve the same result but trim() is more readable.
Time complexity is O(n), space complexity is O(n).
Best Answers
function solution(str) {
return str.trim();
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
