JavaScript trim(), ltrim(), rtrim() Methods
Learn how to remove whitespace from strings in JavaScript using trim(), trimStart(), and trimEnd() methods, with PHP equivalents.
Trimming Whitespace in JavaScript
The trim() method removes whitespace from both ends of a string. JavaScript also provides trimStart() (left trim) and trimEnd() (right trim) for one-sided trimming.
trim() - Remove Both Sides
const str = ' Hello World '; console.log(str.trim()); // 'Hello World' console.log(str.trimStart()); // 'Hello World ' console.log(str.trimEnd()); // ' Hello World'
What Counts as Whitespace?
trim() removes spaces, tabs (\t), newlines (\n), carriage returns (\r), and other Unicode whitespace characters.
const messy = '\t\n Hello \r\n'; console.log(messy.trim()); // 'Hello' // trim does NOT remove inner whitespace const inner = ' Hello World '; console.log(inner.trim()); // 'Hello World'
Custom Trim: Remove Specific Characters
JavaScript's built-in trim only removes whitespace. To trim custom characters, use a regex:
// Remove leading/trailing dashes const str = '---Hello---'; const trimmed = str.replace(/^-+|-+$/g, ''); // 'Hello' // Generic trim function for any character function trimChar(str, ch) { const re = new RegExp(`^[${ch}]+|[${ch}]+$`, 'g'); return str.replace(re, ''); }
PHP Equivalents
In PHP, the equivalent functions are trim(), ltrim(), and rtrim():
<?php $str = " Hello World "; echo trim($str); // "Hello World" echo ltrim($str); // "Hello World " echo rtrim($str); // " Hello World" // PHP trim() can also trim custom characters echo trim("xxHelloxx", "x"); // "Hello"
Browser Support
trim() is supported in all browsers including IE9+. trimStart() and trimEnd() require ES2019+ (all modern browsers). The aliases trimLeft() and trimRight() are deprecated but still work.
Last updated: 2026 • Browse all courses