Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript
communitycreator

How to trim whitespaces in strings in JavaScript

Programming Bytes

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.

RELATED TAGS

javascript
communitycreator
RELATED COURSES

View all Courses

Keep Exploring