Normalize input
Clean user-entered text before validation or storage.
JavaScript · Function
trim() returns a new string with whitespace and line terminators removed from both ends of the string. It leaves the original string unchanged.
Call trim() on a string to create a new string with whitespace and line terminators removed from its beginning and end. The method does not mutate the original string; if no trimming is needed, it still returns a new string.
trim()A new string representing the input string with whitespace removed from its beginning and end.
const raw = " hello, JavaScript!\n";
const clean = raw.trim();
console.log(clean); // "hello, JavaScript!"
console.log(raw); // " hello, JavaScript!\n"This removes whitespace at both ends while leaving the original string unchanged.
Clean user-entered text before validation or storage.
Remove accidental surrounding whitespace from configuration or environment values.
Prepare text for reliable comparisons or display.
String.prototype.trimStart()String.prototype.trimEnd()