Remove All Whitespace from a String in JavaScript

Replacing strings in JavaScript can often be quite difficult. Utilizing the string.replace method to modify every instance may still pose challenges. The task of removing all whitespace can become tedious, especially when dealing with line breaks and tabs. Fortunately, JavaScript's string.replace function supports regular expressions. This tutorial will illustrate the process of removing all whitespace from a string value.

Invoke the replace method on a string in JavaScript, utilizing a regular expression that identifies any whitespace character, and providing an empty string as the replacement to eliminate all whitespace from the string. For example, the function str.replace(/\s/g, "") generates a new string by erasing every whitespace character from str.

Example

const str = '5 6 7';
constwhitespaceRemoved = str.replace(/\s/g, '');
console.log(whitespaceRemoved); // 567

Whitespace characters, including spaces, tabs, and newlines, are matched by the s regex metacharacter.

We can employ the g regex flag to specify that all whitespace characters within the string should be matched. The first whitespace will only be matched and substituted if this flag has not been applied:

Example

const str = '4 5 6';

// No 'g' flag in regex
constwhitespaceRemoved = str.replace(/\s/, '');

// Only first whitespace removed
console.log(whitespaceRemoved); // 45 6

The second parameter provided to the replace function results in every instance of the matches being replaced in the newly returned string. When this second argument is an empty string (""), it leads to the removal of all whitespace by substituting it with nothing, effectively erasing it.

Note: Since strings in JavaScript are immutable, the replace function returns a new string without altering the original string.

Example

const str = '4 5 6';
constwhitespaceRemoved = str.replace(/\s/g, '');

console.log(whitespaceRemoved); // 456

// Not modified
console.log(str); // 4 5 6

Combining the Join and Split methods

One different approach involves splitting the string based on whitespace as the delimiter, and subsequently concatenating the two segments using an empty string. The subsequent example demonstrates this process by removing every uninterrupted space character from the string.

A string can be segmented into multiple smaller substrings through the use of the split method, which provides the output as an array. This method divides the string whenever the designated separator appears within it, with the separator being specified as an argument. For instance, when a space is encountered in the string, the space character (" ") is provided in this parameter to facilitate the separation of the string. Additionally, an array of strings can be combined using a specified separator by utilizing the join method. This method will yield a new string that consists of the concatenated strings, separated by the chosen delimiter. If no separator ("") is designated when this method is applied to the resulting array, it will generate a new string by merging the strings in the array without any spaces in between, effectively filling any gaps present in the original array.

Example

const str = '   Hello World   ';
console.log(str.split(' ').join(''));

/*
    Output: HelloWorld
*/

Utilize the s option to remove all whitespace characters from the string.

Example

const str = '   Hello World   ';
console.log(str.split(/\s+/).join(''));

/*
    Output: HelloWorld
*/

trim

JavaScript provides the capability to utilize the trim function to eliminate any whitespace, which encompasses spaces, tabs, no-break spaces, and all types of line terminators. While this method allows for the complete removal of whitespace from the given string, if your intention is solely to eliminate the whitespace from the beginning or the end of the string, you can make use of the trimStart and trimEnd methods. These methods specify the starting and ending points for the whitespace removal process.

Example

const example ='  Welcome To Example Website  ';

console.log(example.trim());

By utilizing the trimStart and trimEnd functions, we can remove whitespace exclusively from the start or the end of a string, respectively.

Example

const example ='  Welcome To Example Website                  ';

console.log(example.trimStart());

console.log(example.trimEnd());

Conclusion

When dealing with code that spans hundreds of lines, the task of eliminating unnecessary whitespace can become quite daunting. To address this, JavaScript provides an array of methods for removing these extraneous spaces. This article delves into several approaches to strip whitespace from strings. While certain methods remove all spaces indiscriminately, others grant us the flexibility to determine precisely which spaces should be eliminated. Each technique is accompanied by examples and source code to enhance comprehension.

Input Required

This code uses input(). Please provide values below: