This post will discuss how to replace extra whitespaces in a string with a single space in JavaScript.

Whitespace characters are any characters that produce a blank space on the screen, such as spaces, tabs, or newlines. To replace extra whitespaces in a string, we need to use some function or function that can find and replace the whitespace patterns in the string. Here are some of the most common and easy-to-use functions:

1. Using replace() function

This is a simple and straightforward way to replace extra whitespaces in a string with a single space. The replace() function returns a new string with the matched values replaced without changing the original string. It takes two arguments: a pattern to match and a replacement value, where the pattern can be a string or a regular expression. To use it, we need to pass a regular expression that matches two or more whitespace characters (such as spaces, tabs, or newlines) and a new value that is a single space. Here’s an example:

Download  Run Code

 
The regular expression /\s+/g matches one or more whitespace characters (\s+) globally (g), meaning it will find all occurrences in the string. The replacement value is a single space (" "), which will replace each matched substring.

2. Using split() and join() functions

This is another way to replace whitespaces by using the split() function, which splits a string into an array of substrings based on a separator, and the join() function, which joins an array of elements into a string using a separator. The separator can be a string or a regular expression that defines the whitespace pattern. For example, if we want to replace extra whitespaces in a string with a single space in the string "Hello world!", we can write:

Download  Run Code

 
The regular expression /\s+/ matches one or more whitespace characters, as before. The split() function will return an array of substrings that are separated by the whitespace pattern, such as ["Hello", "world!"]. The join() function will return a string that is composed of the array elements joined by the separator, which is a single space (" ").

3. Using custom function

This is a more manual way to replace extra whitespaces in a string with a single space. We can write our own custom function by using a loop, that iterates over the string and removes any extra whitespace. This function works by trimming any leading or trailing whitespace from the string, and then looping over each character in the string. If the character is not a space, it is added to the result. If the character is a space, it is only added to the result if the next character is not also a space. This way, any consecutive spaces are reduced to one space. Here’s an example of this approach:

Download  Run Code

That’s all about replacing extra whitespaces in a string with a single space in JavaScript.