How to Trim String in JavaScript
Published in
4 min readApr 15, 2020
It’s super simple to remove whitespace from a string. To remove just the leading whitespace, you can use trimStart()
. To remove trailing whitespace, use trimEnd()
. Or remove it all with trim()
🙌
const string = " hi ";string.trimStart(); // "hi "
string.trimEnd(); // " hi"
string.trim(); // "hi"
Trim Return Value
All trim methods, will return a new string. That means your original string will be left intact.
const string = " hi ";string.trimStart(); // "hi "
string.trimEnd(); // " hi"
string.trim(); // "hi"string; // " hi "
What is Whitespace
So trim
removes whitespace. So that is the white space created by:
- space
- tab
- no-break space
- line terminator characters
Trimming Line Terminator Characters
You might be wondering what are line terminator characters. Well, let’s take a look at some examples.
'hi \n'.trim(); // "hi"'hi \t'.trim(); // "hi"'hi \r'.trim(); // "hi"