Spaces, tabs, and newlines are among the whitespace characters that the s regex metacharacter matches.
We can utilize the g regex flago to declare that every whitespace character in the string should be matched. The initial whitespace will only be matched and replaced if this flag is not present:
The second argument supplied to the replace() method causes all of the matches in the returned new string to be replaced. The second input is an empty string ("), which causes all the whitespace to be replaced with nothing and therefore eliminated.
Combining the Join() and Split() methods
An alternative strategy is to divide the string using whitespace as a separator and then link the two halves together with an empty string. By erasing every continuous space character from the string, the example that follows shows how this is done.
A string can be divided into several smaller strings using the split() method, which returns the result as an array. To split the string, anytime the specified separator appears in the string, and a separator can be specified as a parameter. When a space appears in the string, the space character (" ") is supplied in this argument to separate the string. An array of strings may be joined together using a separator by using the join() method. The combined string using the chosen separator will be returned as a new string. No separator ("") is used to unite the strings when this method is applied to the returned array. It will create a new string by joining the strings in the array. It will fill up every empty area in the original area.
Use s instead to eliminate all whitespace characters from the string.
Using the trimStart() and trimEnd() methods, we may eliminate whitespace from just the beginning or end of the text, respectively.