JavaScript Program to Remove All Whitespaces From a Text

To understand this example, you should have the knowledge of the following JavaScript programming topics:


Example 1: Using split() and join()

Output

HelloWorld

In the above program,

  • The split(' ') method is used to split the strings into individual array elements.
    ["", "", "", "", "", "", "Hello", "World", "", "", "", "", "", "", ""]
  • The join('') method merges the array into a string.

Example 2: Using Regular Expression

Output

HelloWorld

In the above program, the Regular Expression is used with the replace() method to remove all whitespaces from a text.

/\s/g checks for whitespace in the string.