JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to remove whitespaces from a string in JavaScript?

To remove whitespaces from both ends of a string, you must use the String.prototype.trim() method.

It is important to note that in JavaScript following characters are considered whitespaces:

  • Spaces
  • Tabs
  • Newline
  • Carriage return
  • Form feed

The syntax for the trim() method is

let trimmedString = originalString.trim();

Note: The trim() method does not modify the original string and returns a new string with whitespaces removed from both ends.

The following example removes whitespaces from a string.

let str = "   JavaScript String     ";
let trimmedString = str.trim();

console.log(trimmedString);
console.log(str);

Output

"JavaScript String"
"   JavaScript String     "

Recommended Posts