trimEnd()
ES2019+Removes whitespace from the end of a string.
Syntax
string.trimEnd()Return Value
A new string with whitespace removed from the end
Examples
const str = 'Hello ';
console.log(str.trimEnd()); 📌 When to Use
Use trimEnd() when you need to preserve leading whitespace (like indentation) but remove trailing whitespace, such as when cleaning up lines from files that may have trailing spaces or when preserving code indentation.
⚠️ Common Mistakes
Overusing trimEnd() when trim() would work - only use trimEnd() when you specifically need to preserve leading whitespace.
Not knowing that trimRight() is an alias for trimEnd() - both methods work identically.
Forgetting that newline characters (\n, \r) are also trimmed by trimEnd(), which might not be desired when processing multiline strings.
✅ Best Practices
Use trimEnd() when processing lines from text files to remove trailing whitespace while preserving indentation structure.
Prefer trimEnd() over regex str.replace(/\s+$/, "") for cleaner and more readable code.
When cleaning up user input that might have been copy-pasted, trimEnd() can help remove invisible trailing characters.
⚡ Performance Notes
trimEnd() scans only from the end of the string, making it marginally faster than trim() when you only need trailing whitespace removal. For most practical applications, the performance difference is negligible.
🌍 Real World Example
File Processing and Log Cleaning
trimEnd() is particularly useful when processing configuration files, source code, or logs where you want to remove trailing whitespace while preserving meaningful indentation at the start of lines.
// Clean trailing whitespace from code while preserving indentation
function cleanCodeFile(content) {
return content
.split('\n')
.map(line => line.trimEnd())
.join('\n');
}
const messyCode = `
function example() {
const x = 1;
return x;
}
`;
console.log(cleanCodeFile(messyCode));
// Removes trailing spaces while keeping indentation
// Process log entries with timestamps
function parseLogEntry(line) {
// Preserve leading timestamp/level but remove trailing garbage
const cleaned = line.trimEnd();
const match = cleaned.match(/^(\[.*?\])\s*(.*)$/);
if (match) {
return { timestamp: match[1], message: match[2] };
}
return { timestamp: '', message: cleaned };
}
const logLine = '[2024-01-15 10:30:45] User logged in \t\n';
console.log(parseLogEntry(logLine));
// Output: { timestamp: '[2024-01-15 10:30:45]', message: 'User logged in' }