- Line terminator character (used to improve the readability of the source text)
So, the trim() method removes whitespaces from both the sides of the String. It doesn’t changes the original String.
' Hi Poopcoder!'.trim(); //'Hi Poopcoder!' 'Welcome '.trim(); //'Welcome' ' to learning '.trim(); //'to learning'
Trim Multi-line String:
let multiLine = ` Hai `; multiline.trim(); // "Hai"
let multiLine = ` Let trim multiline `; multiline.trim(); /* Let trim multiline*/
Trim Line Terminator Characters
Below are some examples for Line Terminator Characters, to know more details about Line Terminator click on
trimStart() removes the leading white space. So all the whitespace from the beginning of a string to the first non-whitespace character will be trimmed.
trimLeft() is an alias of this method
let string = " hi "; string.trimStart(); // "hi " string.trimLeft(); // "hi "
trimEnd() removes the trailing whitespace. So all the whitespace from the end of a string will be trimmed. The alias of this method is
let string = " hi "; string.trimEnd(); // " hi" string.trimRight(); // " hi"
trimEnd() are preferred and recommended to use with new ECMAScript code,
trimRight() are compatibility with old code.
You can also use it to remove odd whitespaces in a sentence and format it properly. It makes you sentence much prettier
let sentence = "He threw three free throws "; const prettySentence = sentence .split(' ') // ["He", "", "threw", "", "", "three", "free", "", "throws", ""] .filter(word => word) // ["He", "threw", "three", "free", "throws"] .join(' '); // "He threw three free throws" console.log(prettySentence); // "He threw three free throws"
If your browser doesn’t supports the trim() method, you can use the below Regular Expression to remove whitespace in your string.
trim()– Chrome, Firefox, Safari, Edge, Internet Explorer
trimEnd()– Chrome, Firefox, Safari, Edge