Trim Whitespace Tool
Remove unwanted spaces and tabs from the beginning and end of each line instantly. Our whitespace trimmer cleans up poorly formatted text, code with inconsistent indentation, and data pasted from various sources.
Whitespace Trimming Options
| Mode | Removes | Preserves | Trim BothLeading + trailingInternal spaces Trim LeftLeading spaces/tabsTrailing whitespace Trim RightTrailing spaces/tabsLeading whitespace Collapse SpacesMultiple spaces → singleLine structure | Full Normalize | All excess whitespace | Single spaces only |
Whitespace Trimmer Implementation
``javascript
function trimWhitespace(text, options = {}) {
const {
trimLeft = true,
trimRight = true,
collapseSpaces = false,
normalizeLineEndings = true
} = options;
let lines = text.split('\n');
lines = lines.map(line => {
if (trimLeft) line = line.replace(/^\s+/, '');
if (trimRight) line = line.replace(/\s+$/, '');
if (collapseSpaces) line = line.replace(/ +/g, ' ');
return line;
});
let result = lines.join('\n');
if (normalizeLineEndings) {
result = result.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
}
return {
originalLength: text.length,
trimmedLength: result.length,
bytesRemoved: text.length - result.length,
result
};
}
``
Why Trim Whitespace?
Trailing whitespace causes issues in version control (Git shows unnecessary changes), violates many coding style guides, and can cause bugs in whitespace-sensitive languages like Python and YAML. Leading whitespace inconsistency makes code harder to read and can break indentation-based logic.
Data Cleaning Applications
When copying text from PDFs, websites, or spreadsheets, extra whitespace often comes along. Our trimmer normalizes this text for clean data import. For CSV/TSV files, trimming ensures accurate parsing without phantom empty columns or matching failures.