Code Logo

Trim Whitespace with trim()

Published at25 Jul 2026
JavaScript String Handling Easy 0 views
Like0

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

Example 1
Input
" "
Output
""
Explanation

All whitespace becomes empty

Example 2
Input
" a b c "
Output
"a b c"
Explanation

Internal spaces preserved

Example 3
Input
"\t\n rust \t\n"
Output
"rust"
Explanation

Trim tabs and newlines

Example 4
Input
" hello "
Output
"hello"
Explanation

Trim both sides

Example 5
Input
"abc"
Output
"abc"
Explanation

No whitespace, unchanged

Algorithm Flow

Recommendation Algorithm Flow for Trim Whitespace with trim()
Recommendation Algorithm Flow for Trim Whitespace with trim()

Solution Approach

function solution(str) {
  return str.trim();
}

Best Answers

javascript - Approach 1
function solution(str) {
  return str.trim();
}