Problem Statement
What does the trim() method do?
Explanation
The trim method removes whitespace from both the beginning and end of a string.
Whitespace includes spaces, tabs, and newlines.
It does not remove whitespace from the middle of the string.
Trim returns a new string without modifying the original.
TrimStart removes only leading whitespace. TrimEnd removes only trailing whitespace.
Trim is commonly used to clean user input.
Code Solution
SolutionRead Only
const str = ' Hello World ';
// trim() - removes whitespace from both ends
const trimmed = str.trim();
console.log(trimmed); // 'Hello World'
console.log(str); // ' Hello World ' (unchanged)
// trimStart() / trimLeft() - removes leading whitespace
const trimmedStart = str.trimStart();
console.log(trimmedStart); // 'Hello World '
// trimEnd() / trimRight() - removes trailing whitespace
const trimmedEnd = str.trimEnd();
console.log(trimmedEnd); // ' Hello World'
// Doesn't remove middle whitespace
const text = ' Hello World ';
console.log(text.trim()); // 'Hello World'
// Common use case - clean user input
function processInput(input) {
return input.trim().toLowerCase();
}
const userInput = ' HELLO ';
console.log(processInput(userInput)); // 'hello'
// Remove all whitespace (not just ends)
const removeAll = ' H e l l o ';
console.log(removeAll.replace(/\s/g, '')); // 'Hello'
// Trim works with tabs and newlines
const multiLine = '\n\t Hello \t\n';
console.log(multiLine.trim()); // 'Hello'
// Check if string is empty after trim
function isEmpty(str) {
return str.trim().length === 0;
}
console.log(isEmpty(' ')); // true
console.log(isEmpty(' hi ')); // false