How to remove spaces from a string in javascript

anjan-dutta - May 25 '21 - - Dev Community

Space can be present at any position in a string and, a single solution will not work in every situation.

In this article, I have discussed two ways to:

  • Trim the extra space from the beginning or end of a string.
  • Remove all extra spacing between words.

Trim the extra space from the beginning or end of a string.

Javascript has an inbuild trim() function for this purpose. The trim function takes one parameter, the string itself and, it returns a trimmed string.

The syntax looks like below:

var content = "      The Quick!       ";
console.log(content.trim());
//The Quick!
Enter fullscreen mode Exit fullscreen mode

Simple, right!

Next, you can read how to remove all extra spacing between words from here in my original blog post

. . . . . . . . . . . . . . . . . . . . .