How to trim whitespaces in strings in JavaScript
Trimming whitespaces
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 string
All 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:
- whitespace characters like space, tab, and no-break space.
- line terminator characters like \n, \t, and \r.
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
Removing whitespace in a multi-line string
const multiLine = `I❤️ Educative`;console.log(multiLine.trim());
Alias methods
There are alias methods for the trimStart and trimEnd methods.
trimStarthas alias astrimLefttrimEndhas alias astrimRight
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.