transformation
String.prototype.trim
Returns a new string with whitespace removed from both ends. Whitespace includes spaces, tabs, newlines, and Unicode whitespace like non-breaking space.
str.trim() Parameters
| Parameter | Purpose |
|---|---|
| (no arguments) | Method takes no parameters |
| returns | New string without leading/trailing whitespace |
Examples
console.log(' hello '.trim()); Prints 'hello'
console.log('\n\t hi \r\n'.trim()); Prints 'hi'
console.log('no-trim-needed'.trim()); Prints 'no-trim-needed'
console.log('a b c'.trim()); Prints 'a b c' (interior whitespace untouched)
Gotcha
Only strips leading/trailing whitespace, never interior. Zero-width characters (U+200B) are NOT trimmed — they are not whitespace.
Related methods
String.prototype.trimStart
Returns a new string with leading whitespace removed. Added in ES2019 (aliased as trimLeft for legacy code).
String.prototype.trimEnd
Returns a new string with trailing whitespace removed. Added in ES2019 (aliased as trimRight for legacy code).
String.prototype.replace
Returns a new string with the first match of pattern replaced. Pattern can be a string (only the first occurrence) or a RegExp (all occurrences when the g flag is set).
String.prototype.replaceAll
Returns a new string with every occurrence of pattern replaced. Added in ES2021; if pattern is a RegExp it must have the g flag or replaceAll throws TypeError.
String.prototype.toUpperCase
Returns a new string with all characters converted to upper case using the Unicode default case mapping. Locale-insensitive — use toLocaleUpperCase for language-specific rules (e.g. Turkish i).