Learn how to use a regular expression (regex) in JavaScript to replace all white spaces inside a string effectively.

Replacing white spaces within a string is a common requirement in various scenarios. For instance, I encountered this situation when dealing with an API endpoint that received an image. The original image name was used for storage purposes. However, if the name contained spaces, it caused issues with the functionality (although this can also apply to other special characters, let’s focus on spaces for now).

To address this problem, I conducted some research to find the optimal solution. It turns out that using a regular expression was the best approach. Here’s the solution in its entirety:

const name = 'Hi my name is Flavio';
name.replace(/\s/g, ''); // Output: HimynameisFlavio

How to Replace White Space Inside a String in JavaScript

In JavaScript regular expressions, the \s meta character matches any whitespace character, including spaces, tabs, newlines, and Unicode spaces. The g flag indicates to JavaScript that it should replace all occurrences of whitespace. If you omit the g flag, only the first occurrence of whitespace will be replaced.

Keep in mind that the original name value doesn’t change. If the cleaned string is needed, assign it to a new variable:

const name = 'Hi my name is Flavio';
const nameCleaned = name.replace(/\s/g, '');

Tags: JavaScript, regex, regular expression, string manipulation