Syntax
str.trim()
str.trimStart()
str.trimEnd()Examples
Basic Trimming
Cleaning whitespace from user input.
const input = " hello world ";
console.log(trim = input.trim()); // "hello world"
console.log(input.trimStart()); // "hello world " - only leading removed
console.log(input.trimEnd()); // " hello world" - only trailing removedValidating Trimmed Input
A common real-world pattern for form validation.
function validateUsername(input) {
const trimmed = input.trim();
if (trimmed.length === 0) {
return "Username cannot be empty or just whitespace";
}
return `Valid username: ${trimmed}`;
}
console.log(validateUsername(" ")); // "Username cannot be empty or just whitespace"
console.log(validateUsername(" alice ")); // "Valid username: alice"Best practices
- Always trim() user input before validation checks (like checking for empty strings) to catch whitespace-only submissions
- Trim input before storing it, to avoid inconsistent data caused by accidental leading/trailing spaces
- Use trimStart()/trimEnd() specifically when only one side needs cleaning, such as preserving intentional trailing formatting
- Remember trim() only removes whitespace characters (spaces, tabs, newlines), not other characters like punctuation
Runtime & versions
Browsers and JavaScript runtimes. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
ECMAScript specification