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:

  1. trim: trims whitespace at start and end of the string
  2. trimStart: trims whitespace at the start of the string
  3. trimEnd: 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 start
console.log(msg.trimStart());
// removes white space at the end
console.log(msg.trimEnd());
// removes white space at both the start and the end
console.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 removed
console.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 removed
console.log('Educative \t'.trim()); //tab be removed
console.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.

  • 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 start
console.log("Trim Start -" , msg.trimStart());
console.log("Trim Left - " , msg.trimLeft());
// removes white space at end
console.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.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources