In JavaScript, we can trim whitespaces at the start and end of the string. We have three methods with different functionality to trim the whitespace:
trim
: trims whitespace at start and end of the stringtrimStart
: trims whitespace at the start of the stringtrimEnd
: trims whitespace at the end of the stringAll of the above trim methods will return a new string; so, the original string remains untouched.
const msg = " I love educative ";// removes white space at the startconsole.log(msg.trimStart());// removes white space at the endconsole.log(msg.trimEnd());// removes white space at both the start and the endconsole.log(msg.trim());
The whitespaces removed by the trim
method include:
console.log('Educative \n'); //new-line will be removedconsole.log('A line wil be inserted above this line because of "\\n" ');console.log("So use trim method to remove \\n \\r \\t ...");console.log('Educative \n'.trim()); //new-line will be removedconsole.log('Educative \t'.trim()); //tab be removedconsole.log('Educative \r'.trim()); // new line wil be removed
const multiLine = `I❤️ Educative`;console.log(multiLine.trim());
There are alias methods for the trimStart
and trimEnd
methods.
trimStart
has alias as trimLeft
trimEnd
has alias as trimRight
Both methods have the same implementation.
const msg = " I love educative ";// removes white space at startconsole.log("Trim Start -" , msg.trimStart());console.log("Trim Left - " , msg.trimLeft());// removes white space at endconsole.log("Trim End -" , msg.trimEnd());console.log("Trim Right - " , msg.trimRight());
We can use the trim method when we are getting the value of a text box. The user may have added some whitespace in the input box, which we will remove and process the input value.