trim()
, trimStart()
and trimEnd()
are native JavaScript methods to remove whitespace (space, tab, no-break space, etc) and line terminator characters (LF, CR, etc) from a string. It is usually a good practice to clean up strings entered from the application input.
What is the Difference Between trim(), trimStart() and trimEnd()?
trim()
will remove all whitespaces and line terminators of a stringtrimStart()
will only remove ALL whitespaces and line terminators from the beginning of a stringtrimEnd()
will only remove ALL whitespaces and line terminators from the end of a string
How to Remove Leading and Trailing Spaces and Line Terminators from a String in JavaScript
String.prototype.trim()
will remove all whitespaces and line terminators character from the start and end of the string.
// remove all leading and trailing white spaces
const userName = ' Jay ';
userName.trim(); // => 'Jay'
// remove all leading and trailing line terminators
const userName = '\t Jay\n ';
userName.trim(); // => 'Jay'
How to Remove whitespaces and Line Terminators From the Start of a String in JavaScript
String.prototype.trimStart()
will only remove whitespace and line terminators from the beginning of a string
// remove all leading white spaces
const userName = ' Jay ';
userName.trimStart(); // => 'Jay '
// remove all leading line terminators
const userName = '\t Jay\n ';
userName.trimStart(); // => 'Jay\n '
How to Remove whitespaces and Line Terminators From the End of a String in JavaScript
String.prototype.trimEnd()
will only remove whitespace and line terminators from the end of a string
// remove all trailing white spaces
const userName = ' Jay ';
userName.trimEnd(); // => ' Jay'
// remove all trailing line terminators
const userName = '\t Jay\n ';
userName.trimEnd(); // => '\t Jay'